Skip to content

Commit 48db556

Browse files
committed
Create 234-palindrome-linked-list
1 parent e7dd013 commit 48db556

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

c/0234-palindrome-linked-list.c

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)