The most straightforward and easy-understand solution


  • 0
    L

    My first reaction is stack<>(), last in first one.
    for example . [1,2,3,2,1]
    my stack would be [1,2,3,2,1]
    head.val = stack.pop().val which is the last one in the list.
    O(n) time . O(n) space
    I know is not O(1) space, but it is straightforward

    public class Solution {
    public boolean isPalindrome(ListNode head) {

        Stack<ListNode> stack = new Stack<>();
        if(head==null){
            return true;
        }
        ListNode node = head;
        while(node!=null){
            stack.push(node);
            node=node.next;
        }
        while(head.next!=null){
            if(head.val!=stack.pop().val){
                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.