【问题标题】:Loop in Linked List error while reversing a linked list?反转链接列表时循环链接列表错误?
【发布时间】:2020-07-26 23:15:06
【问题描述】:

我在尝试反转链表时遇到链表循环错误-

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        
        first = head
        second = head.next
        third = head.next.next
        
        while third != None and third.next != None:
            
            third = second.next
            
            second.next = first
            first = second
            second = third

            
        print(first)
        print (second)
            
        return second
        

输出:[5]

错误是-

错误 - 在 ListNode 中找到循环 ListNode{val: 5, next: 无}

【问题讨论】:

  • 知道如何调试这个问题吗?

标签: python-3.x algorithm


【解决方案1】:

如果你仔细观察:

third = second.next

“第三个”值永远不会改变

反向列表应该是怎样的?

通常在反向链表中,头部变为尾部,反之亦然,下一个值指向上一个链接

【讨论】:

猜你喜欢
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 2019-06-17
  • 1970-01-01
相关资源
最近更新 更多