-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPalindrome Linked List.cpp
56 lines (55 loc) · 1.13 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
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 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(!head || !head->next)
{return true;}
ListNode *fast,*slow;
fast=head;
slow=head;
while(fast && fast->next)
{
fast=(fast->next)->next;
slow=slow->next;
}
if(fast)
{slow=slow->next;}
slow=ReverseList(slow);
while(slow)
{
if(head->val!=slow->val)
return false;
head=head->next;
slow=slow->next;
}
return true;
}
ListNode* ReverseList(ListNode* head)
{
if(!head || !head->next)
{return head;}
ListNode *p,*q,*temp;
p=head;
q=head->next;
temp=q->next;
q->next=p;
p->next=NULL;
p=q;
q=temp;
while(q)
{
temp=q->next;
q->next=p;
p=q;
q=temp;
}
return p;
}
};