-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathPalindromeLinkedList.cs
62 lines (56 loc) · 1.76 KB
/
PalindromeLinkedList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* ==============================================================================
* 功能描述:PalindromeLinkedList
* 创 建 者:gz
* 创建日期:2017/4/28 18:49:30
* ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinkedList.Lib
{
/// <summary>
/// PalindromeLinkedList
/// </summary>
public class PalindromeLinkedList
{
//Given a singly linked list, determine if it is a palindrome.
//Follow up:
//Could you do it in O(n) time and O(1) space?
#region 公有方法
public bool IsPalindrome(ListNode head)
{
int nodeCnt = nodeCount(head);
ListNode begNode = head;
//反转后半部分
ListNode midNode = head;
int i = 0;
int mid = nodeCnt % 2 == 0 ? nodeCnt / 2 : nodeCnt / 2 + 1;
while (++i <= mid)
midNode = midNode.next;
i = 0;
LinkesListBasic bas = new LinkesListBasic();
ListNode rmidNode = bas.ReverseList(midNode);
//后半部分反转后,如果是回文,则前半、后半对应元素相等
while (i++ < nodeCnt / 2)
{
if (begNode.val != rmidNode.val)
return false;
begNode = begNode.next;
rmidNode = rmidNode.next;
}
return true;
}
private int nodeCount(ListNode head)
{
int cnt = 0;
while (head != null)
{
cnt++;
head = head.next;
}
return cnt;
}
#endregion
}
}