-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPallindromeCheck.cpp
More file actions
58 lines (48 loc) · 1.31 KB
/
Copy pathPallindromeCheck.cpp
File metadata and controls
58 lines (48 loc) · 1.31 KB
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(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* reverseLinkedList(ListNode* head){
ListNode* curr= head, *ahead, *prev=nullptr;
while(curr){
ahead = curr->next;
curr->next = prev;
prev = curr;
curr = ahead;
}
return prev;
}
public:
bool isPalindrome(ListNode* head) {
if(!head) return true;
ListNode* curr = head;
int count=0;
while(curr){
count++;
curr = curr->next;
}
int leftEnd = count/2;
int rightEnd = count%2 == 0 ? leftEnd: leftEnd+1;
curr = head;
int cnt=0;
while(curr && cnt <rightEnd){
cnt++;
curr= curr->next;
}
ListNode* rightEndNode = reverseLinkedList(curr);
curr = head;
ListNode* curr2 = rightEndNode;
while(curr2){
if(curr->val != curr2->val) return false;
curr = curr->next;
curr2 = curr2->next;
}
return true;
}
};