題目:
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}
.
題解:
題目要重新按照 L0→Ln→L1→Ln-1→L2→Ln-2→…來排列,看例子1->2->3->4會變成1->4->2->3,拆開來看,是{1,2}和{4,3}的組合,而{4,3}是{3,4}的逆序。這樣問題的解法就出來了。
第一步,將連結串列分為兩部分。
第二步,將第二部分連結串列逆序。
第三步,將連結串列重新組合。
程式碼如下:
1 public void reorderList(ListNode head) {
2 if(head==null||head.next==null)
3 return;
4
5 ListNode slow=head, fast=head;
6 ListNode firsthalf = head;
7 while(fast.next!=null&&fast.next.next!=null){
8 slow = slow.next;
9 fast = fast.next.next;
10 }
11
12 ListNode secondhalf = slow.next;
13 slow.next = null;
14 secondhalf = reverseOrder(secondhalf);
15
16 while (secondhalf != null) {
17 ListNode temp1 = firsthalf.next;
18 ListNode temp2 = secondhalf.next;
19
20 firsthalf.next = secondhalf;
21 secondhalf.next = temp1;
22
23 firsthalf = temp1;
24 secondhalf = temp2;
25 }
26
27 }
28
29 public static ListNode reverseOrder(ListNode head) {
30
31 if (head == null || head.next == null)
32 return head;
33
34 ListNode pre = head;
35 ListNode curr = head.next;
36
37 while (curr != null) {
38 ListNode temp = curr.next;
39 curr.next = pre;
40 pre = curr;
41 curr = temp;
42 }
43
44 // set head node's next
45 head.next = null;
46
47 return pre;
48 }
2 if(head==null||head.next==null)
3 return;
4
5 ListNode slow=head, fast=head;
6 ListNode firsthalf = head;
7 while(fast.next!=null&&fast.next.next!=null){
8 slow = slow.next;
9 fast = fast.next.next;
10 }
11
12 ListNode secondhalf = slow.next;
13 slow.next = null;
14 secondhalf = reverseOrder(secondhalf);
15
16 while (secondhalf != null) {
17 ListNode temp1 = firsthalf.next;
18 ListNode temp2 = secondhalf.next;
19
20 firsthalf.next = secondhalf;
21 secondhalf.next = temp1;
22
23 firsthalf = temp1;
24 secondhalf = temp2;
25 }
26
27 }
28
29 public static ListNode reverseOrder(ListNode head) {
30
31 if (head == null || head.next == null)
32 return head;
33
34 ListNode pre = head;
35 ListNode curr = head.next;
36
37 while (curr != null) {
38 ListNode temp = curr.next;
39 curr.next = pre;
40 pre = curr;
41 curr = temp;
42 }
43
44 // set head node's next
45 head.next = null;
46
47 return pre;
48 }
Reference://http://www.programcreek.com/2013/12/in-place-reorder-a-singly-linked-list-in-java/