Reorder List

题目:

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}.

思路:

Reorder List, reverse linkedList I & II, Sort List,还有好几道leetcode的关于链表的题,其实具体考察的就是三个操作。

LinkedList 的 Partition,Reverse 和 Merge

我当时是认真做了一下LinkedList 的merge sort,就对这些操作比较熟练了。

 1     public void reorderList(ListNode head) {
 2         ListNode l2 = partition(head);
 3         ListNode newL2 = reverse(l2);
 4         merge(head, newL2);
 5     }
 6     
 7     private ListNode partition (ListNode head) {
 8         ListNode left = head;
 9         ListNode right = head;
10         ListNode pre = new ListNode(0);
11         while (right != null) {
12             pre = left;
13             left = left.next;
14             right = right.next;
15             if (right != null) {
16                 right = right.next;
17             }
18         }
19         pre.next = null;
20         return left;
21     }
22     
23     private ListNode reverse(ListNode head) {
24         if (head == null || head.next == null) {
25             return head;
26         }
27         ListNode pre = null;
28         ListNode cur = head;
29         ListNode temp = new ListNode(0);
30         while(cur != null) {
31             temp = cur.next;
32             cur.next = pre;
33             pre = cur;
34             cur = temp;
35         }
36         return pre;
37     }
38     private void merge(ListNode l1, ListNode l2) {
39         ListNode temp = new ListNode(0);
40         while (l1 != null && l2 != null) {
41             temp = l1.next;
42             l1.next = l2;
43             l1 = temp;
44             if (l1 == null) {
45                 return;
46             }
47             temp = l2.next;
48             l2.next = l1;
49             l2 = temp;
50             if (l2 == null) {
51                 return;
52             }
53         }
54     }
原文地址:https://www.cnblogs.com/gonuts/p/4518711.html