【问题标题】:LeetCode problem 21: Merge Two Sorted Lists - the first list I create is never processedLeetCode 问题 21:合并两个排序列表 - 我创建的第一个列表从未被处理
【发布时间】:2021-04-29 16:15:58
【问题描述】:

我创建了两个链表,但第一个链表从未在 mergeTwoList() 中处理:

class ListNode:
    def __init__(self,data):
        self.data = data
        self.next = None

def mergeTwoList(l1: ListNode, l2: ListNode) -> ListNode:
        
        cur = ListNode(0)
        ans = cur

        while(l1 and l2):

            print("in loop 1 and 2 :")
            if(l1.data > l2.data):
                print("in if 1 :")
                cur.next = l2
                l2 = l2.next
            else:
                print("in if 2 :")
                cur.next = l1
                l1 = l1.next
            cur = cur.next
        while(l1):

            print("in loop 1  :")
            cur.next = l1
            l1 = l1.next
            cur = cur.next
        while(l2):
            print("in loop  2 :")
            cur.next = l2
            l2 = l2.next
            cur = cur.next
        
        return ans.next


if __name__ == "__main__":
    l1_1 = ListNode(1)
    l1_2 = ListNode(2)
    l1_3 = ListNode(3)

    l1_1.next = l1_2
    l1_2.next = l1_3

    l2_1 = ListNode(4)
    l2_2 = ListNode(5)
    l2_3 = ListNode(6)

    l2_1.next = l2_2
    l2_2.next = l2_3

    while(l1_1 is not None):
        print(l1_1.data)
        l1_1 = l1_1.next

    print("<------>")

    answer = mergeTwoList(l1_1,l2_1)

    while(answer is not None):
        print(answer.data)
        answer = answer.next

结果:

1
2
3

在循环 2 中:
在循环 2 中:
在循环 2 中:
4
5
6

它永远不会通过第一个 while 条件 --> while(l1 and l2)

我怀疑它与 Python 中的类调用有关,但不确定。任何帮助将不胜感激。如果我将此方法放在一个类中,然后在外部调用它,它就可以工作。但是上面的代码失败了。

【问题讨论】:

    标签: python python-3.x algorithm data-structures


    【解决方案1】:

    在你的第一个循环结束时:

       while(l1_1 is not None):
            print(l1_1.data)
            l1_1 = l1_1.next
    

    l1_1None,并传递给你的函数mergeTwoList,l1 是None,所以你在函数中的第一个循环没有进入。

    【讨论】:

    • @newbee123 在这种情况下你能验证答案吗
    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 2018-04-17
    • 2020-12-21
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    相关资源
    最近更新 更多