题目描述:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
算法:
参考评论区的java写的。
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
tmp=ListNode(None)
cur=tmp
#两个表头都不为空时,比较两者的val的大小;类似并归排序。
while (l1!=None and l2!=None):
if l1.val<l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur = cur.next
#两者有任一为空,返回另一个的表头。
if l1==None:
cur.next=l2
else:cur.next=l1
return tmp.next
执行用时 :36 ms, 在所有 python3 提交中击败了99.46%的用户
2020/04/27 打卡
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head=ListNode(None)
tp=head
while l1 and l2:
if l1.val<=l2.val:
tp.next=l1
l1=l1.next
else:
tp.next=l2
l2=l2.next
tp=tp.next
tp.next=l1 if l1 else l2
return head.next