Palindorme Linked List Java By Luv


  • 0
    P
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isPalindrome(ListNode head) {
            Stack<Integer> stack = new Stack<>();
            
            if (head==null || head.next==null){
                return true;
            }
                            
            ListNode slow = head;
            ListNode fast = head;
            
            while (fast!=null&&fast.next!=null){           
                
                stack.push(slow.val);
                slow = slow.next;            
                fast = fast.next.next;               
            }
            
            if (fast!=null){
                slow=slow.next;            
            }
                    
            while (slow!=null){
                
                if (stack.peek()!=slow.val)return false;            
                slow=slow.next;
                stack.pop();            
                
            }
            
            return true;                
        }
    }
    

Log in to reply
 

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