1
+ // 148. 排序链表
2
+
3
+
4
+ /**
5
+ * Definition for singly-linked list.
6
+ * public class ListNode {
7
+ * int val;
8
+ * ListNode next;
9
+ * ListNode() {}
10
+ * ListNode(int val) { this.val = val; }
11
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
12
+ * }
13
+ */
14
+
15
+
16
+ /*
17
+ 递归,归并排序:
18
+ 1、方法功能:通过快慢指针找到链表中点,将链表拆分成两个链表,然后“21.合并两个有序链表”,返回新链表头节点
19
+ 2、终止条件:节点为空 或 下一节点为空,则直接返回该节点,因为至少需要两个节点才能排序
20
+ 3、递归逻辑:传入节点拆分成两个链表后,对两个链表有序合并。拆分后的两个新链表需要同样的操作,因此调用递归方法处理
21
+ */
22
+ class Solution {
23
+ public ListNode sortList (ListNode head ) {
24
+ if (head == null || head .next == null ) {
25
+ return head ;
26
+ }
27
+ ListNode slow = head , fast = head ;
28
+ while (fast .next != null && fast .next .next != null ) {
29
+ slow = slow .next ;
30
+ fast = fast .next .next ;
31
+ }
32
+ ListNode newHead = slow .next ;
33
+ slow .next = null ;
34
+ ListNode left = sortList (head );
35
+ ListNode right = sortList (newHead );
36
+ ListNode root = new ListNode (0 );
37
+ ListNode cur = root ;
38
+ while (left != null && right != null ) {
39
+ if (left .val < right .val ) {
40
+ cur .next = left ;
41
+ left = left .next ;
42
+ } else {
43
+ cur .next = right ;
44
+ right = right .next ;
45
+ }
46
+ cur = cur .next ;
47
+ }
48
+ cur .next = left != null ? left : right ;
49
+ return root .next ;
50
+ }
51
+ }
52
+
53
+
54
+ /*
55
+ 优先级队列升序排序,再弹出节点修改下一指针连接方向
56
+ */
57
+ class Solution {
58
+ public ListNode sortList (ListNode head ) {
59
+ PriorityQueue <ListNode > queue = new PriorityQueue <>((x , y ) -> x .val - y .val );
60
+ while (head != null ) {
61
+ queue .add (head );
62
+ head = head .next ;
63
+ }
64
+ ListNode root = new ListNode (0 );
65
+ ListNode cur = root ;
66
+ while (!queue .isEmpty ()) {
67
+ ListNode node = queue .poll ();
68
+ cur .next = node ;
69
+ cur = cur .next ;
70
+ }
71
+ cur .next = null ;
72
+ return root .next ;
73
+ }
74
+ }
75
+
76
+
77
+ /*
78
+ 节点值存入列表,升序排序,再取出创建节点连接成链表
79
+ */
80
+ class Solution {
81
+ public ListNode sortList (ListNode head ) {
82
+ List <Integer > list = new ArrayList <>();
83
+ while (head != null ) {
84
+ list .add (head .val );
85
+ head = head .next ;
86
+ }
87
+ Collections .sort (list );
88
+ ListNode root = new ListNode (0 );
89
+ ListNode cur = root ;
90
+ for (int val : list ) {
91
+ ListNode node = new ListNode (val );
92
+ cur .next = node ;
93
+ cur = cur .next ;
94
+ }
95
+ return root .next ;
96
+ }
97
+ }
0 commit comments