21. Merge Two Sorted Lists

栏目: Java · 发布时间: 5年前

内容简介:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.Example:Input: 1->2->4, 1->3->4

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4

Output: 1->1->2->3->4->4

难度:easy

题目:

合并两个列表并返回新的列表。新列表由两个列表的片断组成。

思路:直接遍历合并

Runtime: 6 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.

Memory Usage: 30.5 MB, less than 44.63% of Java online submissions for Merge Two Sorted Lists.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0), ptr = head;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                ptr.next = l2;
                ptr = l2;
                l2 = l2.next;
            } else {
                ptr.next = l1;
                ptr = l1;
                l1 = l1.next;
            }
        }
        ptr.next = (l1 != null) ? l1 : l2;
        
        return head.next;
    }
}

以上所述就是小编给大家介绍的《21. Merge Two Sorted Lists》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Modern PHP(中文版)

Modern PHP(中文版)

Josh Lockhart / 安道 / 中国电力出版社 / 2015-9 / 39

PHP正在重生,不过所有PHP在线教程都过时了,很难体现这一点。通过这本实用的指南,你会发现,借助面向对象、命名空间和不断增多的可重用的组件库,PHP已经成为一门功能完善的成熟语言。 本书作者Josh Lockhart是“PHP之道”的发起人,这是个受欢迎的新方案,鼓励开发者使用PHP最佳实践。Josh通过实践揭示了PHP语言的这些新特性。你会学到关于应用架构、规划、数据库、安全、测试、调试......一起来看看 《Modern PHP(中文版)》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器