美文网首页
7、合并两个短list

7、合并两个短list

作者: 九答 | 来源:发表于2020-04-02 10:46 被阅读0次

描述

description

链表题,要用temp标记起始位置,最后输出temp.next。

# 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:
        temp = ListNode(0)
        l = temp
        while l1 and l2:
            if l1.val<l2.val:
                l.next = l1
                l1 = l1.next
            else:
                l.next = l2
                l2 = l2.next
            l = l.next
        l.next = l1 or l2  #最后的值也要插入进去
        
        return temp.next

相关文章

网友评论

      本文标题:7、合并两个短list

      本文链接:https://www.haomeiwen.com/subject/wvvtphtx.html