File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * struct ListNode *next;
6
+ * };
7
+ */
8
+ bool isPalindrome (struct ListNode * head ){
9
+
10
+ // find middle of linked list
11
+ struct ListNode * slow = head , * fast = head ;
12
+ while (fast && fast -> next ){
13
+ slow = slow -> next ;
14
+ fast = fast -> next -> next ;
15
+ }
16
+ // reverse second half
17
+ struct ListNode * prev = NULL ;
18
+ while (slow ){
19
+ struct ListNode * nxt = slow -> next ;
20
+ slow -> next = prev ;
21
+ prev = slow ;
22
+ slow = nxt ;
23
+ }
24
+
25
+ // compare left and right
26
+ struct ListNode * left = head , * right = prev ;
27
+ while (right ){
28
+ if (left -> val != right -> val ){
29
+ return false;
30
+ }
31
+ left = left -> next ;
32
+ right = right -> next ;
33
+ }
34
+ return true;
35
+
36
+ }
You can’t perform that action at this time.
0 commit comments