-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path234palindromeLinkedList.cs
112 lines (97 loc) · 2.96 KB
/
234palindromeLinkedList.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace palindromeLinkedList
{
class Program
{
public class ListNode
{
public int value;
public ListNode next;
public ListNode(int v)
{
value = v;
}
}
static void Main(string[] args)
{
// test case 1:
ListNode n1 = new ListNode(1);
n1.next = new ListNode(2);
n1.next.next = new ListNode(2);
n1.next.next.next = new ListNode(1);
bool res = isPalindrome(n1);
// test case 2:
ListNode n2 = new ListNode(1);
n2.next = new ListNode(2);
n2.next.next = new ListNode(1);
bool res2 = isPalindrome(n2);
}
/*
* Leetcode:
* palindrome linked list
* soource code from blog:
* http://www.programerhome.com/?p=26238
* http://blog.csdn.net/xudli/article/details/46871949
* comment from the blog:
* 可以在找到中点后,将后半段的链表翻转一下,这样我们就可以按照回文的顺序比较了
* convert Java to C#
* Julis's comment:
* 1. the code is very easy to follow
*
*/
public static bool isPalindrome(ListNode head)
{
//input check abcba abccba
if (head == null || head.next == null) return true;
ListNode middle = partition(head);
middle = reverse(middle);
while (head != null && middle != null)
{
if (head.value != middle.value) return false;
head = head.next;
middle = middle.next;
}
return true;
}
private static ListNode partition(ListNode head)
{
ListNode p = head;
while (p.next != null && p.next.next != null)
{
p = p.next.next;
head = head.next;
}
p = head.next;
head.next = null;
return p;
}
/**
* Julia's comment:
* how to reverse a singly linked list
* pre -> cur -> nxt (3rd node)
* 1. save 3rd node before break the link next of cur node
* 2. reverse link of cur's next
* 3. move pre, cur forward one step
*/
private static ListNode reverse(ListNode head)
{
if (head == null || head.next == null) return head;
ListNode pre = head;
ListNode cur = head.next;
pre.next = null;
ListNode nxt = null;
while (cur != null)
{
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}
}