LeetCode 21. Merge Two Sorted Lists

Tag:list

Difficulty:Easy

Problem

21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

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

Solution

链表节点插入问题

先确定首元素较小的链表作为返回结果,遍历另一个链表元素在合适位置插入即可。

注意:假设以链表1为底,最后判断若链表2不为空,附在结果后面。

public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
    if (l1==null){
        return l2;
    }
    if (l2==null){
        return l1;
    }

    ListNode l = l1.val <= l2.val ? l1 : l2;    // 较小的链
    ListNode p = l, pre = l;
    ListNode q = l1.val <= l2.val ? l2 : l1;    // 较大的
    while (p != null && q != null) {
        while (p != null && p.val < q.val) {
            pre = p;
            p = p.next;
        }
        ListNode tmp = q.next;
        q.next = pre.next;
        pre.next = q;
        pre = pre.next;
        q = tmp;
    }
    if (q != null) {
        pre.next = q;
    }
    return l;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值