-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathPalindrome Linked List
58 lines (58 loc) · 1.36 KB
/
Palindrome Linked List
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
57
58
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
int len(ListNode* head){
if(head==NULL){
return 0;
}
return 1+len(head->next);
}
ListNode* reverse(ListNode* head){
if(head==NULL || head->next==NULL){
return head;
}
ListNode* t=head;
ListNode* p=reverse(t->next);
while(t->next!=NULL){
t=t->next;
}
t->next=head;
head->next=NULL;
return p;
}
bool isPalindrome(ListNode* head) {
if(head==NULL){
return true;
}
if(head->next==NULL){
return true;
}
ListNode* temp=head;
int mid=(len(head)+1)/2;
int i=0;
while(i<mid-1){
temp=temp->next;
i++;
}
ListNode* newHead=reverse(temp->next);
temp->next=NULL;
while(head!=NULL && newHead!=NULL){
if(head->val==newHead->val){
head=head->next;
newHead=newHead->next;
}else{
return false;
}
}
return true;
}
};