Share my Java Code using Stack

  • 0
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            Stack<ListNode> st = new Stack<ListNode>();
            ListNode temp = head;
            while(temp != null){
                temp =;
                if(st.pop().val != head.val){
                    return false;
                head =;
            return true;

  • 0

    Nice solution, but you can optimize it further.
    Basically, you just need to compare 2 halfs, so you need to put only one half of the elements on the stack.
    The next half can be compared by simply popping the stack.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.