首页 > 其他 > 详细

21. 合并两个有序链表

时间:2021-08-30 03:35:22      阅读:29      评论:0      收藏:0      [点我收藏+]

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

Example 1:

技术分享图片

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both l1 and l2 are sorted in non-decreasing order.

合并两个有序链表。

给两个有序链表,请将两个链表merge,并且输出的链表也是有序的。

时间O(m + n),两个链表的长度

空间O(1)

 

思路:

用一个dummy node去遍历两个链表,然后比较两者的node.val。

解法类似归并排序的merge过程

merge K个链表

类似题:23题影子题148,做法几乎一模一样

 

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null&&l2==null){
            return null;
        }
        ListNode p1=l1;
        ListNode p2=l2;
        ListNode p3=new ListNode(0);
        ListNode cur=p3;
        while(p1!=null && p2!=null){
            if(p1.val<p2.val){
                cur.next=p1;
                p1=p1.next;          
            }else{
                cur.next=p2;
                p2=p2.next;
            }
             cur=cur.next;
        }
      while(p1!=null){
          cur.next=p1;
          cur=cur.next;
          p1=p1.next;
      }
      while(p2!=null){
          cur.next=p2;
          cur=cur.next;
          p2=p2.next;
      }
      return p3.next;
    }
}

  

 

21. 合并两个有序链表

原文:https://www.cnblogs.com/iwyc/p/15203049.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!