My Java Solution using slow- fast pointer approach


  • 0
    R
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            ListNode fast = head, slow = head;
            Stack<ListNode> stack = new Stack<>();
            while(fast != null && fast.next != null){
                stack.push(slow);
                fast = fast.next.next;
                slow = slow.next;
            }
    // for odd list
            if(fast != null){
                slow = slow.next;
            }
            while(slow != null){
                if(stack.pop().val != slow.val) return false;
                slow = slow.next;
            }
            return true;
        }
    }

  • 0

    This was really smart and simple! Well done.


Log in to reply
 

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