-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindrome linked list
144 lines (89 loc) · 2.44 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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#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;
}
};
*****************************************************************/
// S.C->O(N)
//T.C->O(N)
bool palindrome(vector<int>ans){
int s=0;
int e=ans.size()-1;
while(s<=e){
if(ans[s]!=ans[e]){
return 0;
}
s++;
e--;
}
return 1;
}
bool isPalindrome(LinkedListNode<int> *head) {
// Write your code here.
vector<int>ans;
LinkedListNode<int> *temp=head;
while(temp!=NULL){
ans.push_back(temp->data);
temp=temp->next;
}
return palindrome(ans);
}
/*
T.C->O(N)
S.C->O(1)
LinkedListNode<int> *reverse(LinkedListNode<int> *head) {
// Creating node for remembering previous node in Linked List.
LinkedListNode<int> *reverseHead = NULL;
// Creating temporory node.
LinkedListNode<int> *current = head;
while (current != NULL) {
LinkedListNode<int> *currentNext = current->next;
current->next = reverseHead;
reverseHead = current;
current = currentNext;
}
// Return reverse Linked List.
return reverseHead;
}
bool isPalindrome(LinkedListNode<int> *head) {
LinkedListNode<int> *slow = head;
LinkedListNode<int> *fast = head;
LinkedListNode<int> *prev = head;
// Find the middle node using TORTOISE-HARE-APPROACH.
while (fast != NULL && fast->next != NULL) {
prev = slow;
fast = fast->next->next;
slow = slow->next;
}
if (fast != NULL) {
slow = slow->next;
}
// When there is only one node in given Linked List.
if (slow == NULL) {
return true;
}
// Dividing Linked LIst in two part by pointing prev next to NULL.
prev->next = NULL;
// Now reverse the second half.
LinkedListNode<int> *reverseHead = reverse(slow);
// Iterate through both LinkedList and then compare it.
while (head != NULL) {
if (head->data != reverseHead->data) {
return false;
}
reverseHead = reverseHead->next;
head = head->next;
}
return true;
}
*/