-
Notifications
You must be signed in to change notification settings - Fork 33
/
Palindrome List in CPP
179 lines (75 loc) · 1.7 KB
/
Palindrome List in 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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node(int d)
{
data = d;
}
Node *ptr;
};
// Function to check if the linked list
// is palindrome or not
bool isPalin(Node* head)
{
// Temp pointer
Node* slow= head;
// Declare a stack
stack <int> s;
// Push all elements of the list
// to the stack
while(slow != NULL)
{
s.push(slow->data);
// Move ahead
slow = slow->ptr;
}
// Iterate in the list again and
// check by popping from the stack
while(head != NULL )
{
// Get the top most element
int i=s.top();
// Pop the element
s.pop();
// Check if data is not
// same as popped element
if(head -> data != i)
{
return false;
}
// Move ahead
head=head->ptr;
}
return true;
}
// Driver Code
int main()
{
// Addition of linked list
Node one = Node(1);
Node two = Node(2);
Node three = Node(3);
Node four = Node(2);
Node five = Node(1);
// Initialize the next pointer
// of every current pointer
five.ptr = NULL;
one.ptr = &two;
two.ptr = &three;
three.ptr = &four;
four.ptr = &five;
Node* temp = &one;
// Call function to check
// palindrome or not
int result = isPalin(&one);
if(result == 1)
cout << "isPalindrome is true";
else
cout << "isPalindrome is true";
return 0;
}