Skip to content

Commit 5eee073

Browse files
committed
fix 21,提交148
1 parent 56d9ead commit 5eee073

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

leetcode/src/main/java/com/mistray/link/MergeTwoSortedLists21.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
3030
l1.next = mergeTwoLists(l1.next, l2);
3131
return l1;
3232
} else {
33-
l2.next = mergeTwoLists(l2.next, l2);
33+
l2.next = mergeTwoLists(l2.next, l1);
3434
return l2;
3535
}
3636

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.mistray.link;
2+
3+
/**
4+
* @author ZJY(MistRay)
5+
* @Project algorithm-study
6+
* @Package com.mistray.link
7+
* @create 2020年03月04日 16:44
8+
* @Desc
9+
*/
10+
public class SortList148 {
11+
12+
public ListNode sortList(ListNode head) {
13+
if (head == null || head.next == null) {
14+
return head;
15+
}
16+
ListNode fast = head, slow = head;
17+
while (fast.next != null) {
18+
fast = fast.next.next;
19+
if (fast == null) {
20+
break;
21+
}
22+
slow = slow.next;
23+
}
24+
ListNode right = slow.next;
25+
slow.next = null;
26+
ListNode l1 = sortList(head);
27+
ListNode l2 = sortList(right);
28+
return mergeTwoList(l1, l2);
29+
}
30+
31+
32+
// 该函数可以合并两个链表,并返回头结点
33+
public ListNode mergeTwoList(ListNode l1, ListNode l2) {
34+
if (l1 == null) {
35+
return l2;
36+
}
37+
if (l2 == null) {
38+
return l1;
39+
}
40+
if (l1.val > l2.val) {
41+
l2.next = mergeTwoList(l2.next, l2);
42+
return l2;
43+
} else {
44+
l1.next = mergeTwoList(l1.next, l2);
45+
return l1;
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)