21. 合并两个有序链表

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;
    }
}

  

 

posted @ 2021-08-29 17:22  sherry001  阅读(42)  评论(0编辑  收藏  举报