-
Notifications
You must be signed in to change notification settings - Fork 112
/
0234-PalindromeLinkedList.cs
72 lines (63 loc) · 1.84 KB
/
0234-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
63
64
65
66
67
68
69
70
71
72
//-----------------------------------------------------------------------------
// Runtime: 100ms
// Memory Usage: 28 MB
// Link: https://leetcode.com/submissions/detail/358330538/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class _0234_PalindromeLinkedList
{
public bool IsPalindrome(ListNode head)
{
if (head == null) return true;
var endOfFirstHalf = EndOfFirstHalf(head);
var secondHalf = ReverseList(endOfFirstHalf.next);
ListNode p1 = head, p2 = secondHalf;
var result = true;
while (p2 != null)
{
if (p1.val != p2.val)
{
result = false;
break;
}
p1 = p1.next;
p2 = p2.next;
}
return result;
}
private ListNode EndOfFirstHalf(ListNode head)
{
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode ReverseList(ListNode head)
{
ListNode prev = null, curr = head;
while (curr != null)
{
var next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
}