1- 思路
2- 实现
⭐41. 合并 K 个升序链表——题解思路
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if(len==0){
return null;
}
PriorityQueue<ListNode> pq = new PriorityQueue<>(len,Comparator.comparingInt(a -> a.val));
ListNode dummyHead = new ListNode(-1);
ListNode curNode = dummyHead;
for(ListNode list:lists){
if(list!=null){
pq.add(list);
}
}
while(!pq.isEmpty()){
ListNode node = pq.poll();
curNode.next = node;
curNode = curNode.next;
if(curNode.next!=null){
pq.add(curNode.next);
}
}
return dummyHead.next;
}
}
3- ACM 实现
public class mergeKList {
static class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int x){
val = x;
}
}
public static ListNode mergeKLists(ListNode[] lists){
int n = lists.length;
if(n==0){
return null;
}
PriorityQueue<ListNode> pq = new PriorityQueue<>(n, Comparator.comparingInt(a -> a.val));
ListNode dummyHead = new ListNode(-1);
ListNode currNode = dummyHead;
for(ListNode list:lists){
if(list!=null){
pq.add(list);
}
}
while(!pq.isEmpty()){
ListNode nowNode = pq.poll();
currNode.next = nowNode;
currNode = currNode.next;
if(currNode.next!=null) {
pq.add(currNode.next);
}
}
return dummyHead.next;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入链表个数");
int n = sc.nextInt();
ListNode[] lists = new ListNode[n];
for(int i = 0; i < n;i++){
System.out.println("输入链表长度k");
int k = sc.nextInt();
System.out.println("输入链表元素");
lists[i] = new ListNode(sc.nextInt());
ListNode cur = lists[i];
for(int j =1; j<k;j++){
cur.next = new ListNode(sc.nextInt());
cur = cur.next;
}
}
ListNode forRes = mergeKLists(lists);
while (forRes!=null){
System.out.print(forRes.val+" ");
forRes = forRes.next;
}
}
}