Lintcode 合并两个排序的链表
来源:互联网 发布:远程桌面控制软件 编辑:程序博客网 时间:2024/05/18 03:06
将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。
递归实现:
"""Definition of ListNodeclass ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next"""class Solution: """ @param two ListNodes @return a ListNode """ def mergeTwoLists(self, l1, l2): # write your code here if l1 == None: return l2 if l2 == None: return l1 mergeHead = None if l1.val <= l2.val: mergeHead = l1 mergeHead.next = self.mergeTwoLists(l1.next,l2) elif l2.val < l1.val: mergeHead = l2 mergeHead.next = self.mergeTwoLists(l1,l2.next) return mergeHead
非递归实现:
"""Definition of ListNodeclass ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next"""class Solution: """ @param two ListNodes @return a ListNode """ def mergeTwoLists(self, l1, l2): # write your code here if l1 == None: return l2 if l2 == None: return l1 ptr1 = l1 ptr2 = l2 l = ListNode(0) current = l while(ptr1!= None and ptr2 != None): if ptr1.val < ptr2.val: current.next = ptr1 ptr1 = ptr1.next elif ptr1.val > ptr2.val: current.next = ptr2 ptr2 = ptr2.next else: current.next = ptr1 ptr1 = ptr1.next current = current.next current.next = ptr2 ptr2 = ptr2.next current = current.next if ptr1 == None: current.next = ptr2 else: current.next = ptr1 l = l.next return l
0 0
- Lintcode 合并两个排序的链表
- LintCode 合并两个排序链表
- LintCode 合并两个排序链表
- LintCode -合并两个排序链表
- lintcode-合并两个排序链表 -165
- 合并两个排序链表(LintCode)
- LintCode:合并两个排序链表
- lintcode ----合并两个排序链表
- lintcode,合并两个排序链表
- LintCode 合并两个排序链表
- 合并两个排序链表-LintCode
- lintcode 165 合并两个排序链表
- LintCode : 合并两个排序链表
- [LintCode]165.合并两个排序链表
- LintCode 165合并两个排序链表
- lintcode-合并两个排序链表
- 合并两个排序链表-LintCode
- LintCode 合并两个排序链表
- POJ1703 Find them, Catch them(并查集)
- Uva299——Train Swapping
- onWindowFoucusedChanged
- JVMGC——垃圾收集器的分类
- DRP之旅(2)——当ASP遇到JSP
- Lintcode 合并两个排序的链表
- leetcode 77. Combinations
- CodeForces 332B Maximum Absurdity
- Struts2内建的拦截器
- matlab 轻松绘制出曲线的动画效果
- acm 1012 大数问题
- java中this的用法
- 笔试真题-计算大位数的乘积
- codeforces 610A Pasha and Stick