-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindrome_linked_list.cpp
44 lines (38 loc) · 1.03 KB
/
palindrome_linked_list.cpp
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(nullptr == head || nullptr == head->next){
return true;
}
ListNode *fast = head;
ListNode *slow = head;
while(nullptr != fast->next && nullptr != fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode *last = slow->next;
ListNode *pre = head;
while(nullptr != last->next){
ListNode *tmp = last->next;
last->next = tmp->next;
tmp->next = slow->next;
slow->next = tmp;
}
while(nullptr != slow->next){
slow = slow->next;
if(pre->val != slow->val){
return false;
}
pre = pre->next;
}
return true;
}
};