首页 > 解决方案 > 反转链接列表时循环链接列表错误?

问题描述

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

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: None} 中找到循环

标签: python-3.xalgorithm

解决方案


如果你仔细观察:

third = second.next

“第三”值永远不会改变

反向列表应该如何?

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


推荐阅读