O(1) space Java code


  • 0
    H
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if (head == null) {
                return true;
            }
            ListNode cur = head;
            int n = 1;
            while (cur.next != null) {
                n++;
                cur = cur.next;
            }
            ListNode pre = null;
            ListNode nex = null;
            cur = head;
            for (int i = 0; i < n / 2; ++i) {
                nex = cur.next;
                cur.next = pre;
                pre = cur;
                cur = nex;
            }
            if (n % 2 == 1) {
                cur = cur.next;
            }
            while (cur != null) {
                if (cur.val != pre.val) {
                    return false;
                }
                cur = cur.next;
                pre = pre.next;
            }
            return true;        
        }
    }

  • 0
    F

    Excellent method!


Log in to reply
 

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