-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromeLL.cpp
91 lines (76 loc) · 1.71 KB
/
PalindromeLL.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
83
84
85
86
87
88
89
90
91
#include<bits/stdc++.h>
using namespace std;
struct Node
{
string data;
Node* next;
Node(int x){
data = x;
next = NULL;
}
};
bool isPalindrome(string str) {
int i = 0, j = str.size() - 1;
while(i < j) {
if(str[i++] != str[j--])
return false;
}
return true;
}
bool compute(Node* head) {
Node* ptr = head;
string pal = "";
while(ptr != NULL) {
pal += ptr->data;
ptr = ptr->next;
}
return isPalindrome(pal);
}
// * PoTD: 25-Sept-2024
int sizeOfLL(Node* head) {
int cnt = 0;
Node* ptr = head;
while(ptr != nullptr) {
cnt++;
ptr = ptr->next;
}
return cnt;
}
Node* reverseLinks(Node* &head) {
Node* prevPtr = nullptr, *currPtr = head, *fastPtr = head->next;
while(currPtr != nullptr) {
currPtr->next = prevPtr;
prevPtr = currPtr;
currPtr = fastPtr;
if(fastPtr == nullptr)
break;
fastPtr = fastPtr->next;
}
return prevPtr;
}
bool isPalindrome(Node *head) {
if(!head || !head->next)
return 1;
//* Find size of LL
int n = sizeOfLL(head)/2, cnt = 0;
// cout << "size of LL : " << n << endl;
//* Traverse till size + 1
Node* firstPtr = head, *prevPtr = nullptr;
while(cnt != n) {
cnt++;
prevPtr = firstPtr;
firstPtr = firstPtr->next;
}
prevPtr->next = nullptr;
//* Reverse all nodes after half of the LL is over
Node* lastPtr = reverseLinks(firstPtr);
// cout << "Last Ptr data : " << lastPtr->data << endl;
firstPtr = head;
while(firstPtr != nullptr && lastPtr != nullptr) {
if(firstPtr->data != lastPtr->data)
return false;
firstPtr = firstPtr->next;
lastPtr = lastPtr->next;
}
return true;
}