在 Python 中反转链表时出错

error with reversing linked lists in Python

提问人:ewen 提问时间:9/29/2023 最后编辑:greybeardewen 更新时间:9/29/2023 访问量:54

问:

我一直在尝试编写一个可以反转链表的代码,我想我已经有了反转链表的概念,但我无法将其放入代码中。

理想的结果应该是

4
3
2
1

但我总是自己得到“无”

完整代码:

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

class LinkedList:
    def __init__(self):
        self.head = None
        
    def printLL(self):
        current = self.head
        while current:
           print(current.val)
           current = current.next
    
    
    def append(self, val):
       # creation a new node w value
       newNode = ListNode(val)
       if self.head:
           current = self.head
           # go to the end of the linked list
           while current.next:
               current = current.next
           current.next = newNode

       else:
           self.head = newNode
   
    
    def reverseList(self, head):
        prev , curr = None, head
        while curr:
            tmpval = curr.next
            curr.next = prev
            prev = curr
            curr = tmpval
        return prev
        
testlist = LinkedList()
testlist.head = ListNode(None)
testlist.append(1)
testlist.append(2)
testlist.append(3)
testlist.append(4)
testlist.append(5)
testlist.reverseList(testlist.head.next)

testlist.printLL()

我不确定我哪里出错了。没有显示错误,但我无法获得结果。

python 数据结构 链接列表 singlely-linked-list python-dataclasses

评论

0赞 greybeard 9/29/2023
您需要记录源代码。特别是,的返回值是什么,为什么会传递一个?LinkedList.reverseList()head

答:

0赞 Mahboob Nur 9/29/2023 #1

您需要更新 LinkedList 的 self.head 属性

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

class LinkedList:
    def __init__(self):
        self.head = None
        
    def printLL(self):
        current = self.head
        while current:
           print(current.val)
           current = current.next

    def append(self, val):
       newNode = ListNode(val)
       if self.head:
           current = self.head
           while current.next:
               current = current.next
           current.next = newNode
       else:
           self.head = newNode

    def reverseList(self):
        prev, curr = None, self.head
        while curr:
            tmpval = curr.next
            curr.next = prev
            prev = curr
            curr = tmpval
        self.head = prev  

testlist = LinkedList()
testlist.append(1)
testlist.append(2)
testlist.append(3)
testlist.append(4)
testlist.reverseList()  

testlist.printLL()