zoukankan      html  css  js  c++  java
  • LeetCode--Python合并两个有序链表

    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            newHead = ListNode(0)
            pre = newHead
            while l1 and l2:
                if l1.val<l2.val:
                    pre.next = l1
                    l1 = l1.next
                else:
                    pre.next = l2
                    l2 = l2.next
                pre = pre.next
            if l1:
                pre.next = l1
            elif l2:
                pre.next = l2
            return newHead.next
            
    # 有序链表
    head1 = ListNode(2)
    n1 = ListNode(3)
    n2 = ListNode(4)
    n3 = ListNode(9)
    head1.next = n1
    n1.next = n2
    n2.next = n3
    
    # 有序链表
    head2 = ListNode(3)
    m1 = ListNode(5)
    m2 = ListNode(7)
    m3 = ListNode(8)
    head2.next = m1
    m1.next = m2
    m2.next = m3
    
    s = Solution()
    res = s.mergeTwoLists(head1,head2)
    while res:
        print(res.val)
        res = res.next
    

      

  • 相关阅读:
    vue promise
    vue 数组操作
    vue登录注册切换的坑
    筆記連接
    vue配置jquery和bootstarp
    css的寬高約束
    css框模型
    css居中flex
    css居中
    遍历forEach与map的区别-forEach踩坑记
  • 原文地址:https://www.cnblogs.com/daacheng/p/9041877.html
Copyright © 2011-2022 走看看