21. Merge Two Sorted Lists
2016-06-08 10:28
381 查看
题目:
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.
链接: http://leetcode.com/problems/merge-two-sorted-lists/
一刷,还是需要细心
2/11/2017, Java
ListNode current必须初始化?
最后需要判断还有剩余的list
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.
链接: http://leetcode.com/problems/merge-two-sorted-lists/
一刷,还是需要细心
class Solution(object): def mergeTwoLists(self, l1, l2): dummy_node = ListNode(0) current = dummy_node while l1 and l2: if l1.val <= l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next current.next = l1 if l1 else l2 return dummy_node.next
2/11/2017, Java
ListNode current必须初始化?
最后需要判断还有剩余的list
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; else if (l2 == null) return l1; ListNode head = new ListNode(0); ListNode current = head; while(l1 != null && l2 != null) { if (l1.val < l2.val) { current.next = l1; l1 = l1.next; } else { current.next = l2; l2 = l2.next; } current = current.next; } if (l1 != null) current.next = l1; else current.next = l2; return head.next; } }
相关文章推荐
- 自动make工具--autotools
- JS与Ajax Get和Post在使用上的区别实例详解
- AndroidStudio UnsupportedMethodException Unsupported method: InstantRun.getRestartDexFile().
- Powershell日常AD管理-1
- Linux信号列表详解
- 浅谈JS原生Ajax,GET和POST
- SDUT 1138 单链表操作A
- 互联网广告综述之点击率特征工程
- Dialog自定义样式及使用笔记
- Source Insight加载源码
- Unity中协程的运行
- centos6 安装 php7
- NSJSONReadingOptions参数说明
- JavaScript:正则表达式
- Loadrunner11以Java Vuser进行socket压力测试
- final关键字的应用
- 剑指offer(10)-调整数组顺序使奇数位于偶数前面
- 删除一个月前数据,释放表空间
- SQL语句实现表中字段的组合累加排序
- 基于OpenCL的图像积分图算法改进