Write a Function to check if a singly linked list is palindrome


The code provided is an implementation of a Check_Palindrome class in Java that checks if a linked list is a palindrome or not. The linked list is represented using a Node class with an integer data field and a ptr pointer. The Check_Palindrome class has the following methods:

  • isPalindrome(Node head) : This method checks if the linked list is a palindrome or not. It uses a stack to push the values of the nodes in the linked list in reverse order. Then, it compares the popped values from the stack with the values of the nodes in the original linked list. If all the values match, it sets the ispalin variable to true, indicating that the linked list is a palindrome. Otherwise, it sets ispalin to false and breaks out of the loop. Finally, it returns the value of ispalin.
  • main(String[] args) : This is the main method that creates instances of the Node class and sets up a linked list with values 1, 2, 3, 4, 3, 2, 1. It calls the isPalindrome method with the head of the linked list and prints the result indicating if the linked list is a palindrome or not.
  • Node class: This class represents a node in the linked list. It has an integer data field and a ptr pointer that points to the next node in the linked list. The constructor initializes the data field with the given value and sets the ptr pointer to null.

Source Code

import java.util.*;
class Check_Palindrome
{
	public static void main(String args[])
	{
		Node one = new Node(1);
		Node two = new Node(2);
		Node three = new Node(3);
		Node four = new Node(4);
		Node five = new Node(3);
		Node six = new Node(2);
		Node seven = new Node(1);
		one.ptr = two;
		two.ptr = three;
		three.ptr = four;
		four.ptr = five;
		five.ptr = six;
		six.ptr = seven;
		boolean condition = isPalindrome(one);
		System.out.println("isPalidrome : " + condition);
	}
	static boolean isPalindrome(Node head)
	{
 
		Node slow = head;
		boolean ispalin = true;
		Stack<Integer> stack = new Stack<Integer>();
 
		while (slow != null) {
			stack.push(slow.data);
			slow = slow.ptr;
		}
 
		while (head != null) {
 
			int i = stack.pop();
			if (head.data == i) {
				ispalin = true;
			}
			else {
				ispalin = false;
				break;
			}
			head = head.ptr;
		}
		return ispalin;
	}
}
class Node
{
	int data;
	Node ptr;
	Node(int d)
	{
		ptr = null;
		data = d;
	}
}

Output

isPalidrome : true

Example Programs