链表版本归并排序, 外层sortfindmiddle, 切分链表, 然后partitionMerge合并两个链表

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
63
64
65
66
67
68
69
70
71
72
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
/**
* 链表版本归并排序, 外层sortfindmiddle, 切分链表,
* 然后partitionMerge合并两个链表
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode head2 = findMiddle(head);
ListNode left = sortList(head);
ListNode right = sortList(head2);
return partitionMerge(left, right);
}

private ListNode partitionMerge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode();
ListNode cur = dummy;
while (head1 != null && head2 != null) {
if (head1.val > head2.val) {
cur.next = head2;
head2 = head2.next;
cur = cur.next;
} else {
cur.next = head1;
head1 = head1.next;
cur = cur.next;
}
}

if (head1 != null) {
cur.next = head1;
} else if (head2 != null) {
cur.next = head2;
}

return dummy.next;
}

/**
* 将链表从中间拆分成两个链表 (至少有两个节点)
*/
private ListNode findMiddle(ListNode head) {
ListNode dummy = new ListNode(0 , head);
ListNode slow = dummy, fast = dummy;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode nxt = slow.next;
slow.next = null;
return nxt;
}
}

Comments
Recent Posts
进程树
进程管理
Categories
Website Info
Article Count :
3
Total Word Count :
4.6k
Unique Visitors :
Page Views :
Last Update :