题目描述
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法
1.优先队列
思路
采用简单、暴力的方法,
- 先使用一个优先队列分别收集两个链表中的元素
- 再利用优先队列,优先弹出最小元素的特点,实现排序,并构造新的合并链表。
代码
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// 筛选出两个链表都是空链的情况,返回null
if(l1==null && l2 ==null)
return null;
ArrayList<Integer> lst = new ArrayList<>(); // 数组保存链表中所有元素
while(l1!=null){
lst.add(l1.val);
l1 = l1.next;
}
while(l2!=null){
lst.add(l2.val);
l2 = l2.next;
}
var pq = new PriorityQueue<Integer>(lst); // 优先队列,使用堆来实现,从小到大输出
// 创建合并链表
ListNode head = new ListNode(pq.poll().intValue()), p;
p = head;
while(!pq.isEmpty()){
ListNode tmp = new ListNode(pq.poll().intValue());
p.next = tmp;
p = p.next;
}
return head;
}
2.原地修改法
思路
由于两个链表是顺序的,直接依次循环比较两个链表中的元素大小,将较小值链接加入链表中。直到其中一个链表为空,此时只需要将另外一个链表整段地加入合并链表中即可。
代码
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
else if(l2==null){
return l1;
}
ListNode dum = new ListNode(0);
ListNode cur = dum;
while(l1!=null&&l2!=null){
if(l1.val>=l2.val){
cur.next = l2;
l2 = l2.next;
}
else{
cur.next = l1;
l1 = l1.next;
}
cur = cur.next;
}
if(l1!=null)
cur.next = l1;
else{
cur.next = l2;
}
return dum.next;
}
参考链接
https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/solution/mian-shi-ti-25-he-bing-liang-ge-pai-xu-de-lian-b-2/