算法22 leetcode21 合并两个有序链表

题目

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:

输入:l1 = [], l2 = []
输出:[]
示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

提示:

  • 两个链表的节点数目范围是 [0, 50]
  • -100 <= Node.val <= 100
  • l1 和 l2 均按 非递减顺序 排列

链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnnbp2/
来源:力扣(LeetCode)

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1==null||l2==null) return l2==null ? l1:l2;

        ListNode tmp =l1;//l1插入l2
        while(tmp!=null){
            l2=ckadd(tmp,l2);
            tmp =tmp.next;
        }
        return l2;
    }

    ListNode ckadd(ListNode node,ListNode l2){
        ListNode mm=new ListNode(0,l2);
        ListNode fh=mm;
        
        while(node.val>l2.val){
            mm=l2;
            l2=l2.next;
            if(l2==null){
                mm.next=new ListNode(node.val,null);
                return fh.next;
            }
        }
            mm.next=new ListNode(node.val,l2);
            return fh.next;

    }
}

递归方式

 public ListNode mergeTwoLists(ListNode linked1, ListNode linked2) {
        //只要有一个为空,就返回另一个
        if (linked1 == null || linked2 == null)
            return linked2 == null ? linked1 : linked2;
        //把小的赋值给first
        ListNode first = (linked2.val < linked1.val) ? linked2 : linked1;
        first.next = mergeTwoLists(first.next, first == linked1 ? linked2 : linked1);
        return first;
    }
原文地址:https://www.cnblogs.com/impw/p/15598454.html