Java solution with slow/fast pointer


  • 0
    J
        public void reorderList(ListNode head) {
            if (head == null) return;
            ListNode fast = head, slow = head;
            while (fast.next != null && fast.next.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode prev = null;
            fast = slow.next;
            slow.next = null;
            while (fast != null) {
                ListNode next = fast.next;
                fast.next = prev;
                prev = fast;
                fast = next;
            }
            slow = head;
            while (slow != null && prev != null) {
                ListNode next = slow.next;
                ListNode next2 = prev.next;
                slow.next = prev;
                prev.next = next;
                slow = next;
                prev = next2;
            }
        }
    

Log in to reply
 

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