-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathPalindrome_Linked_List.cpp
82 lines (79 loc) · 1.98 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Recursive
class Solution {
public:
void isPalindrome(ListNode* &head, ListNode* tail, int& left, int right, bool& flag) {
if(!tail or !flag) return;
isPalindrome(head, tail->next, left, right + 1, flag);
if(left >= right) return;
if(head->val != tail->val) {
flag = false;
}
head = head->next;
left++;
}
bool isPalindrome(ListNode* head) {
int i = 0;
bool flag = true;
isPalindrome(head, head, i, 0, flag);
return flag;
}
};
// Reverse the middle half of the list and compare
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head and !head->next) {
return head;
}
ListNode* curr = head;
ListNode* prev = nullptr;
while(curr) {
ListNode* nxt = curr->next;
curr->next = prev;
prev = curr;
head = curr;
curr = nxt;
}
return head;
}
bool isPalindrome(ListNode* head) {
if(!head or !head->next) {
return true;
}
int length = 0;
ListNode* curr = head;
while(curr) {
++length;
curr = curr->next;
}
ListNode* slow = head;
ListNode* fast = head->next;
while(fast) {
slow = slow->next;
fast = fast->next;
if(fast) {
fast = fast->next;
}
}
if(length & 1) {
slow = slow->next;
}
ListNode* secondHalf = reverseList(slow);
while(head and secondHalf) {
if(head->val != secondHalf->val) {
return false;
}
head = head->next;
secondHalf = secondHalf->next;
}
return true;
}
};