Pages

Tuesday, September 30, 2025

Palindrome Linked List using Stacks

 import java.util.Stack;


public class Main {


    // singly linked list

    static class Node {

        char data;

        Node next;


        Node(char data) {

            this.data = data;

            this.next = null;

        }

    } 


        

        // palindrome checker using Stack

        public static boolean isPalindrome(Node head) { 

            Stack<Character> stack = new Stack<>();

            Node temp = head;

            

            

            // Push elements to the stack

            while(temp != null){

                stack.push(temp.data);

                temp = temp.next;

            }

            

            // Pop while comparing

            temp = head;

            while(temp != null){

                if(temp.data != stack.pop()) { // if not matched

                    return false;

                }

                

                temp = temp.next;

            }

            return true; // all matched

        }  

        

        

        

    


    public static void main(String[] args) {

        Node head = new Node('A');

        head.next = new Node('B');

        head.next.next = new Node('C');

        head.next.next.next = new Node('B');

        head.next.next.next.next = new Node('A');

        

        if(isPalindrome(head)) {

            System.out.println("yes, it is a palindrome");

        } else {

            System.out.println("not a palindrome");

        }

        

    }

}


No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...