-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoLists.java
More file actions
47 lines (36 loc) · 974 Bytes
/
MergeTwoLists.java
File metadata and controls
47 lines (36 loc) · 974 Bytes
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
import java.util.PriorityQueue;
/**
* 21 合并两个有序链表
*/
public class MergeTwoLists {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// 从小到大排序
PriorityQueue<ListNode> queue = new PriorityQueue<>(2, (a, b) -> {
return a.val-b.val;
});
if(list1==null) {
return list2;
}
if(list2==null) {
return list1;
}
while (list1!=null) {
ListNode temp = list1;
queue.offer(temp);
list1 = list1.next;
}
while(list2!=null) {
ListNode temp = list2;
queue.offer(temp);
list2 = list2.next;
}
ListNode dummy = new ListNode(-1);
ListNode curr = dummy;
while(!queue.isEmpty()) {
curr.next = queue.poll();
curr = curr.next;
}
curr.next = null;
return dummy.next;
}
}