-
Notifications
You must be signed in to change notification settings - Fork 359
/
Checking if a linked list is Palindrome.txt
86 lines (65 loc) · 1.37 KB
/
Checking if a linked list is Palindrome.txt
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
#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\n";
else
cout<<"isPalindrome is true\n";
return 0;
}