Skip to content

Commit 1486648

Browse files
committed
Time: 474 ms, Memory: 52.1 MB - LeetHub
1 parent a90943c commit 1486648

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* public int val;
5+
* public ListNode next;
6+
* public ListNode(int val=0, ListNode next=null) {
7+
* this.val = val;
8+
* this.next = next;
9+
* }
10+
* }
11+
*/
12+
public class Solution {
13+
public bool IsPalindrome(ListNode head) {
14+
if (head == null)
15+
{
16+
return true;
17+
}
18+
19+
var mid = FindMid(head);
20+
var last = ReverseAfter(mid);
21+
mid.next = null;
22+
23+
ListNode headIterator = head, lastIterator = last;
24+
while (lastIterator != null)
25+
{
26+
if (lastIterator.val != headIterator.val)
27+
{
28+
return false;
29+
}
30+
31+
lastIterator = lastIterator.next;
32+
headIterator = headIterator.next;
33+
}
34+
35+
return true;
36+
}
37+
38+
ListNode ReverseAfter(ListNode node)
39+
{
40+
ListNode current = node, next = current.next;
41+
while (next != null)
42+
{
43+
var secondNext = next.next;
44+
next.next = current;
45+
current = next;
46+
next = secondNext;
47+
}
48+
49+
return current;
50+
}
51+
52+
ListNode FindMid(ListNode head)
53+
{
54+
ListNode mid = head, current = head;
55+
var even = true;
56+
57+
while (current.next != null)
58+
{
59+
if (even)
60+
{
61+
mid = mid.next;
62+
}
63+
64+
current = current.next;
65+
even = !even;
66+
}
67+
68+
return mid;
69+
}
70+
}

0 commit comments

Comments
 (0)