资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Merge Two Sorted Lists

dockerclub / 1410人阅读

摘要:先考虑和有无空集,有则返回另一个。新建链表,指针将和较小的放在链表顶端,然后向后遍历,直到或之一为空。再将非空的链表放在后面。

Problem

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example

Given 1->3->8->11->15->null, 2->null, return 1->2->3->8->11->15->null.

Note

先考虑l1和l2有无空集,有则返回另一个。
新建链表dummy,指针node将l1和l2较小的放在链表顶端,然后向后遍历,直到l1或l2之一为空。再将非空的链表放在node后面。最后返回dummy.next结束。

Solution
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(0), node = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            }
            else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        if (l1 != null) node.next = l1;
        if (l2 != null) node.next = l2;
        return dummy.next;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65703.html

相关文章

  • [LintCode/LeetCode] Merge Sorted Array

    Problem Given two sorted integer arrays A and B, merge B into A as one sorted array. Notice You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements ...

    summerpxy 评论0 收藏0
  • [Leetcode] Merge Two Sorted Lists Merge K Sorted L

    摘要:注意因为堆中是链表节点,我们在初始化堆时还要新建一个的类。代码初始化大小为的堆拿出堆顶元素将堆顶元素的下一个加入堆中 Merge Two Sorted Lists 最新更新请见:https://yanjia.me/zh/2019/01/... Merge two sorted linked lists and return it as a new list. The new list...

    stefanieliang 评论0 收藏0
  • LeetCode Easy】021 Merge Two Sorted Lists

    摘要:为减小空间复杂度,最后结果直接修改在上,不重新给分配空间。 Easy 021 Merge Two Sorted Lists Description: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes o...

    icattlecoder 评论0 收藏0
  • leetcode21 Merge Two Sorted Lists 将两个有序链表组合成一个新的有

    摘要:题目要求翻译过来就是将两个有序的链表组合成一个新的有序的链表思路一循环在当前两个链表的节点都是非空的情况下比较大小,较小的添入结果链表中并且获得较小节点的下一个节点。 题目要求 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing togeth...

    BothEyes1993 评论0 收藏0
  • Leetcode 21 Merge Two Sorted Lists

    摘要:题目详情题目要求我们将两个有序链表合成一个有序的链表。输入输出想法首先要判断其中一个链表为空的状态,这种情况直接返回另一个链表即可。每次递归都会获得当前两个链表指针位置的值较小的节点,从而组成一个新的链表。 题目详情 Merge two sorted linked lists and return it as a new list. The new list should be mad...

    xbynet 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<