输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode current = new ListNode(0);
        while(l1 != null || l2 != null){
            //判断l1 和 l2哪个大
            if(l1 != null && l2 != null){
                if(l1.val >= l2.val){
                    current.next = new ListNode(l2.val);
                    l2 = l2.next;
                } else {
                    current.next = new ListNode(l1.val);
                    l1 = l1.next;
                }
            } else if(l1 == null){
                current.next = new ListNode(l2.val);
                l2 = l2.next;
            } else {
                current.next = new ListNode(l1.val);
                l1 = l1.next;
            }
            if(head == null){
                head = current;
            }
            current = current.next;
        }
        if(head == null){
            return null;
        }
        return head.next;
    }

    //时间复杂度O(n)
    //空间复杂度O(1) 只用了两个指针,结果不计算在内

 

相关文章:

  • 2021-08-10
  • 2022-01-08
  • 2022-02-07
  • 2022-12-23
  • 2021-10-03
猜你喜欢
  • 2021-05-31
  • 2022-01-04
  • 2021-07-06
  • 2021-12-12
  • 2021-11-22
  • 2021-12-22
  • 2021-09-21
相关资源
相似解决方案