-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path34. PallindromeLL.cpp
53 lines (45 loc) · 1.24 KB
/
34. PallindromeLL.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
#include <bits/stdc++.h>
/****************************************************************
Following is the class structure of the LinkedListNode class:
template <typename T>
class LinkedListNode
{
public:
T data;
LinkedListNode<T> *next;
LinkedListNode(T data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
LinkedListNode<int> *rev (LinkedListNode<int> *head){
LinkedListNode<int> * prev = nullptr, *curr = head;
while(curr!=NULL){
LinkedListNode<int> *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
bool isPalindrome(LinkedListNode<int> *head) {
if(head == NULL || head->next == NULL)return true;
LinkedListNode<int> * slow = head, * fast = head;
while(fast!=NULL and fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
if (fast != NULL) {
slow = slow->next;
}
LinkedListNode<int> *f = rev(slow);
slow = head;
while(f!=NULL){
if(slow->data!=f->data)return false;
slow = slow->next;
f = f->next;
}
return true;
}