-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpalindrome_linkedlist.cpp
43 lines (39 loc) · 1.12 KB
/
palindrome_linkedlist.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverse(ListNode* head){
//if(!head) return NULL;
ListNode *next = NULL, *prev = NULL;
while(head != NULL){
next = head->next;
head->next = prev;
prev = head;
head = next;
}
//head = prev;
return prev;
}
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
ListNode *fastptr = head, *slowptr = head;
while(fastptr->next != NULL && fastptr->next->next != NULL){
slowptr = slowptr->next;
fastptr = fastptr->next->next;
}
slowptr->next = reverse(slowptr->next);
slowptr = slowptr->next; //slow == pre here.. now compare
while(slowptr!=NULL){
if(head->val != slowptr->val)return false;
slowptr = slowptr->next;
head = head->next;
}
return true;
}
};