Share my AC clean JAVA solution


  • 1
    W
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if (head == null) return true;
            ListNode slow = head;
            ListNode fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode head2 = fast == null ? reverse(slow) : reverse(slow.next);
            while (head2 != null) {
                if (head2.val != head.val) return false;
                head = head.next;
                head2 = head2.next;
            }
            return true;
        }
        
        private ListNode reverse(ListNode head) {
            ListNode preHead = new ListNode(0);
            ListNode cur = head;
            while (cur != null) {
                ListNode tmp1 = preHead.next;
                preHead.next = cur;
                ListNode tmp2 = cur.next;
                cur.next = tmp1;
                cur = tmp2;
            }
            return preHead.next;
        }
    }

Log in to reply
 

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