合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。 请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
思路:
首先我们创建一个链表遍历lists把值给我们新创建的链表,最后我们在对这个链表进行排序就可以得到我们答案!
代码:
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null){
return null;
}
ListNode newHead = new ListNode(); //创建一个虚拟头结点
ListNode cur = newHead; //用于遍历
//遍历lists把值装入我们新创建的链表中
for(ListNode list : lists){
while(list!=null){
cur.next = new ListNode(list.val);
cur = cur.next;
list = list.next;
}
}
ListNode head = f1(newHead.next);
return head;
}
//链表排序方法 head:传入的头结点
public ListNode f1(ListNode head){
if(head == null){
return null;
}
ListNode newhead = head;
ListNode nodeA = newhead;
ListNode nodeB = nodeA.next;
while(nodeA.next!=null){
while(nodeB!=null){
if(nodeB.val < nodeA.val){
int val = nodeA.val;
nodeA.val = nodeB.val;
nodeB.val = val;
}
nodeB = nodeB.next;
}
nodeA = nodeA.next;
nodeB = nodeA.next;
}
return newhead;
}
}