Skip to content

Commit fd45363

Browse files
authored
Create 234. Palindrome Linked List (#436)
2 parents 47d879d + 46dbd87 commit fd45363

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

234. Palindrome Linked List

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
bool isPalindrome(ListNode* head) {
14+
ListNode* fast = head;
15+
ListNode* slow = head;
16+
ListNode* prev = NULL;
17+
18+
while(fast && fast -> next) {
19+
ListNode* temp = slow -> next;
20+
fast = fast -> next -> next;
21+
slow -> next = prev;
22+
prev = slow;
23+
slow = temp;
24+
}
25+
if(fast)
26+
slow = slow -> next;
27+
while(prev && slow) {
28+
if(prev -> val != slow -> val)
29+
return false;
30+
31+
prev = prev -> next;
32+
slow = slow -> next;
33+
}
34+
35+
return true;
36+
}
37+
};

0 commit comments

Comments
 (0)