LeetCode in Python-21. Merge Two Sorted Lists 合并两个有序链表
题目
解法1、
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
curr = dummy = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
if __name__ == "__main__":
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
r = Solution().mergeTwoLists(l1, l2)
while r:
print(r.val)
r = r.next
1、两个变量指向新链表,curr用来更新链表
解法2、
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val > l2.val: l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
出处
1、https://www.bilibili.com/video/av45843264
2、对应题目下Knife丶的题解
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 452966517@qq.com
文章标题:LeetCode in Python-21. Merge Two Sorted Lists 合并两个有序链表
文章字数:215
本文作者:Night Zhang
发布时间:2019-07-26, 17:33:52
最后更新:2019-07-26, 17:35:00
原始链接:https://night-zhang.github.io/2019/07/26/LeetCode-in-Python-21-Merge-Two-Sorted-Lists-合并两个有序链表/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。