-
Notifications
You must be signed in to change notification settings - Fork 0
/
22 March.cpp
42 lines (32 loc) · 931 Bytes
/
22 March.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
class Solution {
public:
ListNode* reverse(ListNode* ptr){
ListNode* pre = NULL;
ListNode* next = NULL;
while(ptr){
next = ptr->next;
ptr->next = pre;
pre = ptr;
ptr = next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL) return true;
ListNode* slow = head;
ListNode* fast = head;
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
slow->next = reverse(slow->next);
slow = slow->next;
ListNode* dummy = head;
while(slow){
if(dummy->val != slow->val) return false;
dummy = dummy->next;
slow = slow->next;
}
return true;
}
};