Share my Java Code using Stack


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

  • 0
    I

    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.