-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindromicLL.cpp
45 lines (44 loc) · 1.18 KB
/
PalindromicLL.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
class Solution {
public:
ListNode*getMid( ListNode*head){
ListNode*slow=head;
ListNode*fast=head->next;
while(fast!=NULL && fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
ListNode*reverse(ListNode*head){
ListNode*prev=NULL;
ListNode*curr=head;
ListNode*forward=NULL;
while(curr!=NULL){
forward=curr->next;
curr->next=prev;
prev=curr;
curr=forward;
}
return prev;
}
bool isPalindrome(ListNode* head) {
if(head->next==NULL){
return true;
}
ListNode*middle=getMid(head);
ListNode*temp=middle->next;
middle->next=reverse(temp);
ListNode*head1=head;
ListNode*head2=middle->next;
while(head2!=NULL){
if(head1->val!=head2->val){
return false;
}
head1=head1->next;
head2=head2->next;
}
temp=middle->next;
middle->next=reverse(temp);
return true;
}
};