内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 21. Merge Two Sorted Lists
- [swift] LeetCode 21. Merge Two Sorted Lists
- LeetCode 第21题 Merge Two Sorted Lists(Java)
- Leetcode基础刷题之PHP解析(21. Merge Two Sorted Lists)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C语言编程:一本全面的C语言入门教程(第三版)
(美)Stephen Kochan / 张小潘 / 电子社博文视点资讯有限公司 / 2006年 / 59.00元
本书是极负盛名的C语言入门经典教材,其第一版发行至今已有20年的历史。本书内容详实全面,由浅入深,示例丰富,并在每个章节后面附有部分习题,非常适合读者自学使用。除此之外,《C语言编程》一书对于C语言标准的最新进展、C语言常见开发工具以及管理C语言大型项目等重要方面,也进行了深入浅出的说明。一起来看看 《C语言编程:一本全面的C语言入门教程(第三版)》 这本书的介绍吧!