Loading

LeetCode 21 合并两个有序列表

LeetCode21 合并两个有序列表

题目描述

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

注意题目:两个升序链表

样例

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

算法分析

  • 遍历两个链表,当都不为空的时候,cur.next = min

  • 当有一个为空的时候,cur.next = l2(l2不空)

时间复杂度\(O(n+m)\)

Java代码

/**
 * 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) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while(l1 != null && l2!=null){
            if(l1.val < l2.val){
                cur.next = new ListNode(l1.val);
                l1 = l1.next;
                cur = cur.next;
            }else{
                cur.next = new ListNode(l2.val);
                l2 = l2.next;
                cur = cur.next;
            }
        }

        if(l1!=null) cur.next = l1;
        if(l2!=null) cur.next = l2;

        return dummy.next;
    }
}
posted @ 2020-10-28 16:50  想用包子换论文  阅读(84)  评论(0)    收藏  举报