【LeetCode】打卡–Python3算法21. 合并两个有序链表
题目
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
结果
执行用时 : 60 ms, 在Merge Two Sorted Lists的Python3提交中击败了81.33% 的用户
内存消耗 : 13.2 MB, 在Merge Two Sorted Lists的Python3提交中击败了53.98% 的用户
Python解答
# 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:
l3 = ListNode(None)
l = l3
while(l1 and l2):
if(l1.val <= l2.val):
l.next = l1
l = l.next
l1 = l1.next
else:
l.next = l2
l = l.next
l2 = l2.next
if (l1 == None):
l.next = l2
else:
l.next = l1
return l3.next
我们下次再见,如果还有下次的话!!!
欢迎关注微信公众号:516数据工作室