File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * struct ListNode *next;
6
+ * };
7
+ */
8
+
9
+ struct ListNode * merge (struct ListNode * list1 , struct ListNode * list2 ) {
10
+ struct ListNode * head , * tail ;
11
+
12
+ if (!list1 || !list2 ) {
13
+ if (!list1 ) {
14
+ return list2 ;
15
+ }
16
+ return list1 ;
17
+ }
18
+
19
+ if (list1 -> val < list2 -> val ) {
20
+ head = list1 ;
21
+ list1 = list1 -> next ;
22
+ } else {
23
+ head = list2 ;
24
+ list2 = list2 -> next ;
25
+ }
26
+ tail = head ;
27
+
28
+ while (list1 && list2 ) {
29
+ if (list1 -> val < list2 -> val ) {
30
+ tail -> next = list1 ;
31
+ list1 = list1 -> next ;
32
+ } else {
33
+ tail -> next = list2 ;
34
+ list2 = list2 -> next ;
35
+ }
36
+ tail = tail -> next ;
37
+ }
38
+
39
+ if (list1 ) {
40
+ tail -> next = list1 ;
41
+ }
42
+
43
+ if (list2 ) {
44
+ tail -> next = list2 ;
45
+ }
46
+
47
+ return head ;
48
+ }
49
+
50
+ // Split a linked list in two halfs:
51
+ struct ListNode * split (struct ListNode * head ) {
52
+ struct ListNode * slow = head , * fast = head , * prev = NULL ;
53
+
54
+ while (fast && fast -> next ) {
55
+ prev = slow ;
56
+ slow = slow -> next ;
57
+ fast = fast -> next -> next ;
58
+ }
59
+
60
+ prev -> next = NULL ;
61
+ return slow ;
62
+ }
63
+
64
+ struct ListNode * sortList (struct ListNode * head ) {
65
+ if (!head || !head -> next ) {
66
+ return head ;
67
+ }
68
+
69
+ return merge (sortList (head ), sortList (split (head )));
70
+ }
You can’t perform that action at this time.
0 commit comments