Do not need reverse,Use the Stack


  • 0
    Y

    This is my solution,

    public class Solution {
        public boolean isPalindrome(ListNode node) {
           if(node==null)
                return true;
            if(node.next==null)
                return true;
            Stack<ListNode> stack = new Stack<>();
            int count = 0;
            ListNode p =  node;
            while (p!=null){
                count++;
                p = p.next;
            }
    
            p = node;
            int i=0;
            while (p!=null&&i<count/2){
                stack.add(p);
                p= p.next;
                i++;
            }
            if(count%2==1){
                p=p.next;
            }
    
            while (p!=null){
                ListNode q = stack.pop();
                if(q.val!=p.val){
                    return false;
                }
                p = p.next;
            }
    
            return true;
        }
    }
    

Log in to reply
 

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