[Approach - 1] Using Stack - O(n) Time and O(n) Space
The idea is to use stack and start traversing from the head node. Push all the node and then start comparing from the head node with top value of stack.
Steps to solve the problem:
Push all the node's data into the stack.
Again traverse from the head node.
Compare the popped node's data with the current node's data.
If both are not equal ,return false .
If all elements match ,return true.
Below is the implementation of the above approach :
C++
#include<iostream>#include<stack>usingnamespacestd;classNode{public:intdata;Node*next;Node(intd){data=d;next=nullptr;}};// Function to check if the linked list // is palindrome or notboolisPalindrome(Node*head){Node*currNode=head;// Declare a stackstack<int>s;// Push all elements of the list to the stackwhile(currNode!=nullptr){s.push(currNode->data);currNode=currNode->next;}// Iterate in the list again and check by// popping from the stackwhile(head!=nullptr){// Get the topmost elementintc=s.top();s.pop();// Check if data is not same as popped elementif(head->data!=c){returnfalse;}// Move aheadhead=head->next;}returntrue;}intmain(){// Linked list : 1->2->3->2->1Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(2);head->next->next->next->next=newNode(1);boolresult=isPalindrome(head);if(result)cout<<"true\n";elsecout<<"false\n";return0;}
Java
importjava.util.Stack;classNode{intdata;Nodenext;Node(intd){data=d;next=null;}}classGfG{// Function to check if the linked list// is palindrome or notstaticbooleanisPalindrome(Nodehead){NodecurrNode=head;Stack<Integer>s=newStack<>();// Push all elements of the list to the stackwhile(currNode!=null){s.push(currNode.data);currNode=currNode.next;}// Iterate in the list again and check// by popping from the stackwhile(head!=null){// Get the topmost elementintc=s.pop();// Check if data is not same as// popped elementif(head.data!=c){returnfalse;}// Move aheadhead=head.next;}returntrue;}publicstaticvoidmain(String[]args){// Linked list : 1->2->3->2->1Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);booleanresult=isPalindrome(head);if(result)System.out.println("true");elseSystem.out.println("false");}}
Python
classNode:def__init__(self,data):self.data=dataself.next=None# Function to check if the linked list # is palindrome or notdefisPalindrome(head):curr_node=heads=[]# Push all elements of the list to the stackwhilecurr_nodeisnotNone:s.append(curr_node.data)curr_node=curr_node.next# Iterate in the list again and check by'# popping from the stackwhileheadisnotNone:# Get the topmost elementc=s.pop()# Check if data is not same as popped elementifhead.data!=c:returnFalse# Move aheadhead=head.nextreturnTrue# Linked list : 1->2->3->2->1head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(2)head.next.next.next.next=Node(1)result=isPalindrome(head)ifresult:print("true")else:print("false")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intd){data=d;next=null;}}// Class to check if the linked list // is palindrome or notclassGfG{// Function to check if the linked list // is palindrome or notstaticboolisPalindrome(Nodehead){NodecurrNode=head;Stack<int>s=newStack<int>();// Push all elements of the list to the stackwhile(currNode!=null){s.Push(currNode.data);currNode=currNode.next;}// Iterate in the list again and check by// popping from the stackwhile(head!=null){// Get the topmost elementintc=s.Pop();// Check if data is not same as // popped elementif(head.data!=c){returnfalse;}// Move aheadhead=head.next;}returntrue;}staticvoidMain(string[]args){// Linked list : 1->2->3->2->1Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);boolresult=isPalindrome(head);if(result)Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to check if the linked list is // palindrome or notfunctionisPalindrome(head){letcurrNode=head;letstack=[];// Push all elements of the list to the stackwhile(currNode!==null){stack.push(currNode.data);currNode=currNode.next;}// Iterate in the list again and check by // popping from the stackwhile(head!==null){// Get the topmost elementletc=stack.pop();// Check if data is not same as popped elementif(head.data!==c){returnfalse;}// Move aheadhead=head.next;}returntrue;}// Linked list : 1->2->3->2->1lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);letresult=isPalindrome(head);if(result)console.log("true");elseconsole.log("false");
Output
true
[Approach - 2] Using Recursion - O(n) Time and O(n) Space
The idea is to initialize a pointer start, which will initially point to the head of the node. Then, recursively traverse the list. At each node end, first recursively check if the right side of the list is palindrome. If yes, then compare the values of the start and end node. If they are equal, then set start = start.nextand return true. Otherwise return false.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intd){data=d;next=nullptr;}};// Recursive Function to check whether // the list is palindromeboolisPalindromeRecur(Node*end,Node*&start){// base caseif(end==nullptr)returntrue;// Recursively check the right side.boolright=isPalindromeRecur(end->next,start);// Compare the start and end nodes.boolans=right&&start->data==end->data;// Update the start node start=start->next;returnans;}// Function to check whether the list is palindromeboolisPalindrome(Node*head){// Set starting node to headNode*start=head;// Recursively check the ll and returnreturnisPalindromeRecur(head,start);}intmain(){// Linked list : 1->2->3->2->1Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(2);head->next->next->next->next=newNode(1);boolresult=isPalindrome(head);if(result)cout<<"true"<<endl;elsecout<<"false"<<endl;return0;}
Java
classNode{intdata;Nodenext;Node(intd){data=d;next=null;}}classGfG{// Recursive Function to check whether // the list is palindromestaticbooleanisPalindromeRecur(Nodeend,Node[]start){// base caseif(end==null)returntrue;// Recursively check the right side.booleanright=isPalindromeRecur(end.next,start);// Compare the start and end nodes.booleanans=right&&start[0].data==end.data;// Update the start node start[0]=start[0].next;returnans;}// Function to check whether the list is palindromestaticbooleanisPalindrome(Nodehead){// Set starting node to headNode[]start=newNode[]{head};// Recursively check the ll and returnreturnisPalindromeRecur(head,start);}publicstaticvoidmain(String[]args){// Linked list : 1->2->3->2->1Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);booleanresult=isPalindrome(head);if(result)System.out.println("true");elseSystem.out.println("false");}}
Python
classNode:def__init__(self,data):self.data=dataself.next=None# Recursive Function to check whether # the list is palindromedefisPalindromeRecur(end,start):# base caseifendisNone:returnTrue# Recursively check the right side.right=isPalindromeRecur(end.next,start)# Compare the start and end nodes.ans=rightandstart[0].data==end.data# Update the start nodestart[0]=start[0].nextreturnans# Function to check whether the list is palindromedefisPalindrome(head):# Set starting node to headstart=[head]# Recursively check the ll and returnreturnisPalindromeRecur(head,start)if__name__=="__main__":# Linked list : 1->2->3->2->1head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(2)head.next.next.next.next=Node(1)result=isPalindrome(head)ifresult:print("true")else:print("false")
C#
classNode{publicintdata;publicNodenext;publicNode(intd){data=d;next=null;}}classGfG{// Recursive Function to check whether // the list is palindromestaticboolisPalindromeRecur(Nodeend,refNodestart){// base caseif(end==null)returntrue;// Recursively check the right side.boolright=isPalindromeRecur(end.next,refstart);// Compare the start and end nodes.boolans=right&&start.data==end.data;// Update the start node start=start.next;returnans;}// Function to check whether the list is palindromestaticboolisPalindrome(Nodehead){// Set starting node to headNodestart=head;// Recursively check the ll and returnreturnisPalindromeRecur(head,refstart);}staticvoidMain(string[]args){// Linked list : 1->2->3->2->1Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);boolresult=isPalindrome(head);if(result)System.Console.WriteLine("true");elseSystem.Console.WriteLine("false");}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Recursive Function to check whether // the list is palindromefunctionisPalindromeRecur(end,start){// base caseif(end===null)returntrue;// Recursively check the right side.letright=isPalindromeRecur(end.next,start);// Compare the start and end nodes.letans=right&&start[0].data===end.data;// Update the start node start[0]=start[0].next;returnans;}// Function to check whether the list is palindromefunctionisPalindrome(head){// Set starting node to headletstart=[head];// Recursively check the ll and returnreturnisPalindromeRecur(head,start);}// Linked list : 1->2->3->2->1lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);letresult=isPalindrome(head);if(result)console.log("true");elseconsole.log("false");
Output
true
[Expected Approach] Using Iterative Method - O(n) Time and O(1) Space
The approach involves reversing the second half of the linked list starting from the middle. After reversing, traverse from the headof the list and the head of the reversed second half simultaneously, comparing the node values. If all corresponding nodes have equal values, the list is a palindrome.
Follow the steps below to solve the problem:
Use two pointers , fast and slow to find the middle of the list. fast will move twosteps ahead and slowwill move one step ahead at a time.
if list is odd, when fast->next is NULL , slow will point to the middle node.
if list is even, when fast->next->next is NULLslow will point to the middlenode.
Reverse the second half of the list starting from the middle.
Check if the first half and the reversed second half are identical by comparingthe node values.
Below is the implementation of the above approach:
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intd){data=d;next=nullptr;}};// Function to reverse a linked listNode*reverse(Node*head){Node*prev=nullptr;Node*curr=head;Node*next;while(curr){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to check if two lists are identicalboolisIdentical(Node*n1,Node*n2){for(;n1&&n2;n1=n1->next,n2=n2->next)if(n1->data!=n2->data)return0;// returning 1 if data at all nodes are equal.return1;}// Function to check whether the list is palindromeboolisPalindrome(Node*head){if(!head||!head->next)returntrue;// Initialize slow and fast pointersNode*slow=head;Node*fast=head;// Move slow to the middle of the listwhile(fast->next&&fast->next->next){slow=slow->next;fast=fast->next->next;}// Split the list and reverse the second halfNode*head2=reverse(slow->next);slow->next=nullptr;// End the first half// Check if the two halves are identicalboolret=isIdentical(head,head2);// Restore the original listhead2=reverse(head2);slow->next=head2;returnret;}intmain(){// Linked list : 1->2->3->2-> 1Nodehead(1);head.next=newNode(2);head.next->next=newNode(3);head.next->next->next=newNode(2);head.next->next->next->next=newNode(1);boolresult=isPalindrome(&head);if(result)cout<<"true\n";elsecout<<"false\n";return0;}
C
#include<stdlib.h>structNode{intdata;structNode*next;};// Function to reverse a linked liststructNode*reverse(structNode*head){structNode*prev=NULL;structNode*curr=head;structNode*next;while(curr){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to check if two lists are identicalintisIdentical(structNode*n1,structNode*n2){for(;n1&&n2;n1=n1->next,n2=n2->next)if(n1->data!=n2->data)return0;// returning 1 if data at all nodes are equal.return1;}// Function to check whether the list is palindromeintisPalindrome(structNode*head){if(!head||!head->next)return1;structNode*slow=head,*fast=head;while(fast->next&&fast->next->next){slow=slow->next;fast=fast->next->next;}structNode*head2=reverse(slow->next);slow->next=NULL;intret=isIdentical(head,head2);head2=reverse(head2);slow->next=head2;returnret;}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){// Linked list : 1->2->3->2->1structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(2);head->next->next->next->next=createNode(1);intresult=isPalindrome(head);if(result)printf("true\n");elseprintf("false\n");return0;}
Java
classNode{intdata;Nodenext;Node(intd){data=d;next=null;}}// Class to check if the linked list is palindrome or notclassGfG{// Function to reverse a linked liststaticNodereverseList(Nodehead){Nodeprev=null;Nodecurr=head;Nodenext;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to check if two lists are identicalstaticbooleanisIdentical(Noden1,Noden2){while(n1!=null&&n2!=null){if(n1.data!=n2.data)returnfalse;n1=n1.next;n2=n2.next;}returntrue;}// Function to check whether the list is palindromestaticbooleanisPalindrome(Nodehead){if(head==null||head.next==null)returntrue;Nodeslow=head,fast=head;while(fast.next!=null&&fast.next.next!=null){slow=slow.next;fast=fast.next.next;}Nodehead2=reverseList(slow.next);slow.next=null;booleanret=isIdentical(head,head2);head2=reverseList(head2);slow.next=head2;returnret;}publicstaticvoidmain(String[]args){// Linked list : 1->2->3->2->1Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);booleanresult=isPalindrome(head);if(result)System.out.println("true");elseSystem.out.println("false");}}
Python
classNode:def__init__(self,d):self.data=dself.next=None# Function to reverse a linked listdefreverse(head):prev=Nonecurr=headwhilecurr:next_node=curr.nextcurr.next=prevprev=currcurr=next_nodereturnprev# Function to check if two lists are identicaldefisIdentical(n1,n2):whilen1andn2:ifn1.data!=n2.data:returnFalsen1=n1.nextn2=n2.nextreturnTrue# Function to check whether the list is palindromedefisPalindrome(head):ifheadisNoneorhead.nextisNone:returnTrueslow,fast=head,head# Find the middle of the listwhilefast.nextandfast.next.next:slow=slow.nextfast=fast.next.next# Split the list and reverse the second halfhead2=reverse(slow.next)slow.next=None# Check if the two halves are identicalret=isIdentical(head,head2)# Restore the original listhead2=reverse(head2)slow.next=head2returnretif__name__=="__main__":# Linked list : 1->2->3->2->1head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(2)head.next.next.next.next=Node(1)result=isPalindrome(head)ifresult:print("true")else:print("false")
C#
usingSystem;classNode{publicintData;publicNodeNext;publicNode(intd){Data=d;Next=null;}}classGfG{// Function to reverse a linked liststaticNodereverseList(Nodehead){Nodeprev=null;Nodecurr=head;while(curr!=null){Nodenext=curr.Next;curr.Next=prev;prev=curr;curr=next;}returnprev;}// Function to check if two lists are identicalstaticboolisIdentical(Noden1,Noden2){while(n1!=null&&n2!=null){if(n1.Data!=n2.Data)returnfalse;n1=n1.Next;n2=n2.Next;}returntrue;}// Function to check whether the list is palindromestaticboolisPalindrome(Nodehead){if(head==null||head.Next==null)returntrue;Nodeslow=head,fast=head;// Find the middle of the listwhile(fast.Next!=null&&fast.Next.Next!=null){slow=slow.Next;fast=fast.Next.Next;}// Split the list and reverse the second halfNodehead2=reverseList(slow.Next);slow.Next=null;// Check if the two halves are identicalboolret=isIdentical(head,head2);// Restore the original listhead2=reverseList(head2);slow.Next=head2;returnret;}staticvoidMain(){// Linked list : 1->2->3->2->1Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(2);head.Next.Next.Next.Next=newNode(1);boolresult=isPalindrome(head);Console.WriteLine(result?"true":"false");}}
JavaScript
classNode{constructor(d){this.data=d;this.next=null;}}// Function to reverse a linked listfunctionreverseList(head){letprev=null;letcurr=head;while(curr){letnext=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to check if two lists are identicalfunctionisIdentical(n1,n2){while(n1&&n2){if(n1.data!==n2.data){returnfalse;}n1=n1.next;n2=n2.next;}returntrue;}// Function to check whether the list is palindromefunctionisPalindrome(head){if(head===null||head.next===null){returntrue;}// Initialize slow and fast pointersletslow=head;letfast=head;// Find the middle of the linked listwhile(fast!==null&&fast.next!==null){slow=slow.next;fast=fast.next.next;}// Reverse the second half of the listlethead2=reverseList(slow);// Check if the two halves are identicalletret=isIdentical(head,head2);// Restore the original listreverseList(head2);returnret;}// Linked list : 1->2->3->2->1lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(2);head.next.next.next.next=newNode(1);letresult=isPalindrome(head);if(result){console.log("true");}else{console.log("false");}