Palindrome Linked List using Stack albeit with space complexity O(n)


  • 0
    A
    
    // Palindrome Linked List using Stack.
    // Time complexity O(n) and Space complexity O(n).
    public boolean isPalindrome(ListNode head) {
            Stack<Integer> myStack = new Stack<>();
            ListNode dummy = head;
            while(dummy != null) {
                myStack.push(dummy.val);
                dummy = dummy.next;
            }
            
            while(head != null) {
                if(head.val != myStack.pop())
                    return false;
                head = head.next;
            }
            
            return true;
        }
    

Log in to reply
 

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