4

#yyds干货盘点# LeetCode 热题 HOT 100:合并K个升序链表

 1 year ago
source link: https://blog.51cto.com/u_13321676/5696887
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# LeetCode 热题 HOT 100:合并K个升序链表

精选 原创

灰太狼_cxh 2022-09-21 17:19:39 博主文章分类:leetcode ©著作权

文章标签 链表 升序 数组 文章分类 Java 编程语言 阅读数170

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

输入: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

输入:lists = []

输出:[]

输入:lists = [[]]

输出:[]

代码实现:

class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode ans = null;
for (int i = 0; i < lists.length; ++i) {
ans = mergeTwoLists(ans, lists[i]);
}
return ans;
}

public ListNode mergeTwoLists(ListNode a, ListNode b) {
if (a == null || b == null) {
return a != null ? a : b;
}
ListNode head = new ListNode(0);
ListNode tail = head, aPtr = a, bPtr = b;
while (aPtr != null && bPtr != null) {
if (aPtr.val < bPtr.val) {
tail.next = aPtr;
aPtr = aPtr.next;
} else {
tail.next = bPtr;
bPtr = bPtr.next;
}
tail = tail.next;
}
tail.next = (aPtr != null ? aPtr : bPtr);
return head.next;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK