[Naive Approach] Using Stack - O(n) Time and O(n) Space
Push all node into a stack.
Start comparing from the head node with top value of stack.
Move forward in Linked List and remove the top from stack after comparison.
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
[Expected Approach] Reverse Second Half - 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 head of 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 two steps 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 NULL, slow 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;}}// 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 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;while(fast.next!=null&&fast.next.next!=null){slow=slow.next;fast=fast.next.next;}Nodehead2=reverseList(slow.next);slow.next=null;boolret=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);boolresult=isPalindrome(head);if(result)Console.WriteLine("true");elseConsole.WriteLine("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");}