How to check if linked list is palindrome in java

In this post, we will see how to check if linked list is palindrome or not.

Java Linked List Interview Programs:

    How to reverse a linked list in java How to reverse a linked list in pairs in java How to find middle element of linked list in java How to detect a loop in linked list in java Find start node of loop in linkedlist How to find nth element from end of linked list How to check if linked list is palindrome in java Add two numbers represented by linked list in java


Java Program:

package org.arpit.java2blog;

public class LinkedListPalindromeCheck{

 private Node head;

 private static class Node {
  private int value;
  private Node next;

  Node(int value) {
   this.value = value;


 public void addToTheLast(Node node) {

  if (head == null) {
   head = node;
  } else {
   Node temp = head;
   while ( != null)
    temp =; = node;

 public void printList() {
  Node temp = head;
  while (temp != null) {
   System.out.format("%d ", temp.value);
   temp =;

 // This function will find middle element in linkedlist
 public static Node findMiddleNode(Node head)
  // step 1
  Node slowPointer, fastPointer; 
  slowPointer = fastPointer = head; 

  while(fastPointer !=null) { 
   fastPointer =; 
   if(fastPointer != null && != null) { 
    slowPointer =; 
    fastPointer =; 

  return slowPointer; 
 // Function to check if linked list is palindrome or not
 public static boolean checkPalindrome (Node head)
  // Find middle node using slow and fast pointer
  Node middleNode=findMiddleNode(head);
  // we got head of second part
  // It is end of first part of linked list;
  // get reversed linked list for second part
  Node reverseSecondHead=reverseLinkedList(secondHead);

  while(head!=null && reverseSecondHead!=null)
    return false;

  return true;


 public static Node reverseLinkedList(Node currentNode)  
  // For first node, previousNode will be null  
  Node previousNode=null;  
  Node nextNode;  
   // reversing the link;  
   // moving currentNode and previousNode by 1 node  
  return previousNode;  

 public static void main(String[] args) {
  LinkedListPalindromeCheck list = new LinkedListPalindromeCheck();
  // Creating a linked list
  Node head=new Node(1);
  list.addToTheLast(new Node(2));
  list.addToTheLast(new Node(1));
  list.addToTheLast(new Node(2));
  list.addToTheLast(new Node(1));


  System.out.println("Linked list palidrome: "+checkPalindrome(head));

When you run above program, you will get following output:
1 2 1 2 1 
Linked list palidrome: true

Time complexity : O(n)
Space complexity : O(1)

Please go through java interview programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012