LeetCode 143 - Reorder List - 题解/Solution

https://leetcode.com/problems/reorder-list/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* 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}.
*
* @author dongyuxi
*
*/
public class Solution {
public ListNode reorderList(ListNode head) {
if (null == head || null == head.next) {
return head;
}

// find the middle of list
ListNode slowIndex = head;
ListNode fastIndex = head.next;
while (null != fastIndex && null != fastIndex.next) {
slowIndex = slowIndex.next;
fastIndex = fastIndex.next.next;
}

// reverse the second half of list
slowIndex.next = reverseList(slowIndex.next);

// reorder the first half and the second half
ListNode firstHalf = head;
ListNode secondHalf = slowIndex.next;
slowIndex.next = null;
while (null != secondHalf) {
ListNode firstHalfNext = firstHalf.next;
ListNode secondHalfNext = secondHalf.next;
firstHalf.next = secondHalf;
secondHalf.next = firstHalfNext;
firstHalf = firstHalfNext;
secondHalf = secondHalfNext;
}

return head;
}

private ListNode reverseList(ListNode head) {
if (null == head || null == head.next) {
return head;
}
ListNode prev = head;
ListNode cur = head.next;
while (null != cur) {
ListNode next = cur.next;
cur.next = prev;
if (prev == head) {
prev.next = null;
}
prev = cur;
cur = next;
}
return prev;
}
}


支付宝 微信
文章目录