forked from GFGSC-RTU/GFG-SDE-Sheet-Solution-Kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request GFGSC-RTU#50 from s-bh/s-bh
Create palindrome-linked-list.cpp
- Loading branch information
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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; | ||
} |