×

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome

In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome.

Example:

          1 -> 2 -> 3 -> 3 -> 2 -> 1       

Output:

True

Method 1: Using a Stack

In this method, we will use the stack of linked list nodes and perform the following steps:

  • First, it will traverse the entire linked list from the first to the last node and push every visited node to the stack.
  • Next, it will traverse the linked list one more time. After this, it will pop a node from the stack and compare the data of popped node with the node which is visited currently.
  • Finally, if data is matched of all nodes, it returns true, else false.

Java Program to implement the Method 1

 import java.util.*;
 class Node
 {
             int data;
             Node next;
             Node(int d)
             {
                         data = d;
                         next = null;
             }
 }
 public class Palindrome
 {          
 /* Function to print linked list */
     void printList(Node head)
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data+" ");
            temp = temp.next;
         } 
         System.out.println();
     }
 /* Check whether the linked list is palindrome or not */
    boolean isPalindrome(Node head)
    {
         Node temp = head;
         boolean flag = true;
         Stack<Integer> stack = new Stack<Integer>();
         while (temp != null) {
             stack.push(temp.data);
             temp = temp.next;
         }
         while (head != null) {
             int i = stack.pop();
             if (head.data == i) {
                 flag = true;
             }
             else {
                 flag = false;
                 break;
             }
             head = head.next;
         }
         return flag;
     }     
             public static void main(String args[])
             {
                         Scanner sc = new Scanner(System.in);
                         System.out.println("Enter the total no of elements in linked list: ");
                                     int n = sc.nextInt();
                         System.out.println("Enter the elements of linked list: ");
                                     int a1 = sc.nextInt();
                                     Palindrome ob = new Palindrome();
                                     Node head = new Node(a1);
                                                Node tail  =  head;
                                                for (int i  =  1; i < n; i++)
                                     {
                                        int a  =  sc.nextInt();
                                         tail.next  =  new Node(a);
                                         tail  =  tail.next;
                                     }
                                     if(ob.isPalindrome(head) == true)
                                         System.out.println("True");
                             else
                                         System.out.println("False");      
             }
 } 

Output: -

Singly Linked List is Palindrome

Method 2: By reversing the linked list

This method uses the following steps to check the palindrome:

  • It will first find the middle node of the linked list:
  • Then, it will reverse the second half of the given linked list
  • After this, it will compare the nodes of the first half and the second half to be the same or not.
  • Then, we will make the original linked list as it is.

Java Program to implement the Method 2

 import java.util.*;
 class Node
 {
             int data;
             Node next;
             Node(int d)
             {
                         data = d;
                         next = null;
             }
 }
 public class Palindrome
 {
 Node head,slow, fast, second;
 /* Function to print linked list */
     void traverse(Node head)
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data+" ");
            temp = temp.next;
         }
         System.out.println();
     }
 /* Check whether the linked list is palindrome or not */
    boolean isPalindrome(Node head)
    {
         slow = head;
         fast = head;
         Node prev_of_slow = head;
         Node middle = null;
         boolean res = true;
         if (head != null && head.next != null) {
             while (fast != null && fast.next != null) {
                 fast = fast.next.next;
                 prev_of_slow = slow;
                 slow = slow.next;
             }
             if (fast != null) {
                 middle = slow;
                 slow = slow.next;
             }
             second = slow;
             prev_of_slow.next = null;
             reverse();
             res = compareLists(head, second);
                  /* Construct the original list back */
             reverse();
             if (middle != null) {
                 prev_of_slow.next = middle;
                 middle.next = second;
             }
             else
                 prev_of_slow.next = second;
         }
         return res;
     }
 /* Function for reverse the linked list */
     void reverse()
     {
         Node prev = null;
         Node current = second;
         Node next;
         while (current != null) {
             next = current.next;
             current.next = prev;
             prev = current;
             current = next;
         }
         second = prev;
     }
     /* Function for compare both halves of the linked list*/
     boolean compareLists(Node head1, Node head2)
     {
         Node temp1 = head1;
         Node temp2 = head2;
         while (temp1 != null && temp2 != null) {
             if (temp1.data == temp2.data) {
                 temp1 = temp1.next;
                 temp2 = temp2.next;
             }
             else
                 return false;
         }
          if (temp1 == null && temp2 == null)
             return true;
          return false;
     }
             public static void main(String args[])
             {
                         Scanner sc = new Scanner(System.in);
                         System.out.println("Enter the total no of elements in linked list: ");
                                     int n = sc.nextInt();
                         System.out.println("Enter the elements of linked list: ");
                                     int a1 = sc.nextInt();
                                     Palindrome ob = new Palindrome();
                                     Node head = new Node(a1);
                                                Node tail  =  head;
                                                for (int i  =  1; i < n; i++)
                                     {
                                        int a  =  sc.nextInt();
                                         tail.next  =  new Node(a);
                                         tail  =  tail.next;
                                     }
                                     if(ob.isPalindrome(head) == true)
                                         System.out.println("True");
                             else
                                         System.out.println("False");
             }
 } 

Output:

Singly Linked List is Palindrome


Related Topics

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Polish Notation in Data Structures

Arithmetic Expression: An arithmetic expression is defined as several operands or data items combined using several operators. For example; a+b*(c-d) is an expression. Operands: Operands represent the data in an expression...

2 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Threaded Binary Trees

Introduction Threaded Binary Trees (TBTs) are an enhancement of normal binary trees intended for in-order traversal only. This means that this data structure is developed with the objective of making the...

12 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree. Implementation #include <bits/stdc++.h> using namespace std; /* A binary tree node...

4 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

AVL tree in data structure c++

AVL tree is generally known as the self-sustained and most balanced tree in the field of a binary search tree. It was also widely known as the height-balanced binary tree....

6 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Dijkstra’s vs Bellman-Ford Algorithm

The Dijkstra Algorithm One of the SSSP (Single Source Shortest Path) algorithms is Dijkstra's. As a result, it finds the shortest path between a source node and all other nodes in...

7 minutes read.