LeetCode Merge Two Sorted Lists
来源:互联网 发布:淘宝店铺收藏链接转换 编辑:程序博客网 时间:2024/05/12 15:15
Description:
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.
Solution:
Remember the very important step in the merge sort? About merging two arrays. This one is almost the same, every time we get the smaller one of the remaining tow head.
Be careful when at least one of the lists is empty.
public class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode head;if (l1 == null)return l2;if (l2 == null)return l1;if (l1.val < l2.val) {head = l1;l1 = l1.next;head.next = null;} else {head = l2;l2 = l2.next;head.next = null;}ListNode tot = head, next;while (l1 != null && l2 != null) {if (l1.val < l2.val) {next = l1;l1 = l1.next;next.next = null;} else {next = l2;l2 = l2.next;next.next = null;}tot.next = next;tot = tot.next;}if (l1 != null)tot.next = l1;if (l2 != null)tot.next = l2;return head;}}
0 0
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- Leetcode Merge Two Sorted Lists
- 2015062003 - 关羽
- 九度1475 - IP数据包解析(北邮)
- bootstrap的选择列表和表单
- C语言单链表的实现
- C语言一个双向链表的实现
- LeetCode Merge Two Sorted Lists
- 【麦可网】Cocos2d-X跨平台游戏开发学习笔记---第十一课:Cocos2D-X坐标系统2-3
- 判断是否微信 IPhone 打开
- 认识脱壳:一切从“壳”开始
- Linux字符设设备编程(四)之可爱的misc
- leetcode:Linked List Cycle
- Effective C++条款16解读:成对使用new和delete时要采取相同形式
- 解密系列(系统篇_PE结构详讲笔记6)
- 数据结构——循环队列(c++)