×

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

Delete nodes from the linked list which have a greater value on the right side

Delete nodes from the linked list which have a greater value on the right side In this problem, we have given a singly linked list, and we need to remove all...

3 minutes read.

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 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.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

3 minutes read.

What is the difference between DFS and BFS?

What is BFS? BFS is generally known as the low level traversal. As we already know that it stands for breadth first search and is mainly used in the queue data...

4 minutes read.

Timsort

TimSort Time Complexity Timsort is a sorting algorithm that is quite efficient for real-world data. Timsort is created in 2001 by Tim Peters for the python programming language. Timsort is a...

3 minutes read.

Find the fractional (n/kth) node in the linked list

Find the fractional (n/kth) node in the linked list In this problem, we have given a singly linked list and a number k. Here we need to find the (n/k)th element...

2 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Queue operations in Data Structure

Queue - Queue is a linear data structure or first in first out data structure means the first element added in the queue will be removed first and the last...

7 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Why is Binary Heap Preferred over BST for Priority Queue

A priority queue is a linear and ordered collection of elements in which each element has an attribute named priority and the priority attribute decides the order in which elements...

2 minutes read.

Sort the linked list of 0s, 1s and 2s

Sort the linked list of 0s, 1s and 2s In this, we are given a linked list of 0s, 1s, and 2s, and we need to sort it. Examples: Input: 1  ->  1 ...

2 minutes read.