100 likes | 268 Views
Reorder List. Agenda. Problem description Key idea Complete code. Problem Description. Given a singly linked list L : L 0 → L 1 →…→ L n -1 → L n , reorder it to: L 0 → L n → L 1 → L n -1 → L 2 → L n -2 →… You must do this in-place without altering the nodes' values.
E N D
Agenda • Problem description • Key idea • Complete code
Problem Description • Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… • You must do this in-place without altering the nodes' values. • For example,Given {1,2,3,4}, reorder it to {1,4,2,3}. • Source: http://oj.leetcode.com/problems/reorder-list/
Why need to find out mid? • Find the mid of a list. • Reason: mid is like a separating point: elements after mid will be inserted into the corresponding positions before mid. • Challenge: put the elements to be inserted (they are after mid) in the ascending order by the positions to be inserted. mid head tail
Key idea: find mid and tail • Given a list, find its mid and tail element. • Use slow and fast pointers, as long as fast is not the tail element, every time fast moves two steps, then, after fast moves for the second time, slow moves one step. • When fast reaches the last element (ie. Tail) of the linked list, slow is in the mid. mid head tail
Key idea: reverse nodes after mid • In the following example, 7, 6, and 5 need to insert into the corresponding position of the first half the list. • Key: reverse nodes after mid to the rest of list. mid head tail
Complete code publicvoidreorderList(ListNode head) { //Single out the list with at most two nodes (no process is needed.) if (head == null || head.next == null || head.next.next == null) return; //Now there are at least three nodes in the list. //Use slow and fast to find out mid and tail node. ListNode slow = head; ListNode fast = head; while (fast.next != null) { fast = fast.next; if (fast.next != null) { fast = fast.next; slow = slow.next; } } This case can be included in the following process. fast is not the last node in the list Only when fast moves for the second time, can slow moves for the first time.
Complete Code: II reverse(slow.next, fast); //key! slow.next = null; //Insert the nodes in fast to head alternatively. ListNodeinsPoint = head; ListNode temp, temp2; while (fast != null) { temp = insPoint.next; //(1) insPoint.next = fast; //(2) temp2 = fast.next; //(3) fast.next = temp; //(4) //Update insPoint and node to insert. insPoint = temp; //(5) fast = temp2; //(6) } } insPoint temp (1) temp2 (2) (4) (3)
Complete Code: III void reverse(ListNode start, ListNode end) { ListNodetoMove = start; ListNode temp; while (toMove != end) { temp = toMove.next; toMove.next = end.next; end.next = toMove; toMove = temp; } } end toMove