forked from Nivedpv2004/C-PROGRAMING
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Palindrom_linked_list
57 lines (44 loc) · 1.06 KB
/
Palindrom_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
/* Program to check whether a given linked list is a palindrome or not.
Example: 3->4->4->3 is a palindrome
Approach used: Double traversal of linked list with stack */
#include<bits/stdc++.h>
using namespace std;
struct node{
int val;
struct node *next;
node(int val){
this->val=val;
next=NULL;
}
};
bool palindrome(node *head){
stack<int> stk;
if(head==NULL)
return true;
node *temp=head;
while(temp->next){
stk.push(temp->val);
temp=temp->next;
}
while (head != NULL) {
int value = stk.top();
stk.pop();
if (head->val!=value) {
return false;
}
head = head->next;
}
return true;
}
int main(){
node *head=new node(3);
head->next=new node(4);
head->next->next=new node(3);
head->next->next->next=new node(3);
bool isPalindrome=palindrome(head);
if(isPalindrome)
cout<<"Linked list is a palindrome";
else
cout<<"Linked list is not a palindrome";
return 0;
}