Python 中反转链表的错误

问题描述 投票:0回答:1

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

理想的结果应该是

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 data-structures linked-list singly-linked-list python-dataclasses
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.