python 使用递归反转链接列表

8gsdolmq  于 2023-02-07  发布在  Python
关注(0)|答案(1)|浏览(135)

我正在使用递归来反转链表,但是没有得到结果。每当我对输入[1,2,3,4,5,6,-1]使用下面的代码时,它会显示结果[1->None]。我没有得到我犯错误的地方。请帮助我。

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

def takeInput():
    inputList = [int(ele) for ele in input().split()]
    head = None
    for i in inputList:
        if i == -1:
            break
        newNode = Node(i)
        if head is None:
            head = newNode
            tail = newNode
        else:
            tail.next = newNode
            tail = newNode
    return head

def printLL(head):
    while head is not None:
        print(str(head.data) + "->", end="")
        head = head.next 
    print("None")
    return

def reverseLL(head):
    if head is None or head.next is None:
        return head
    rest = reverseLL(head.next)
    head.next.next = head
    head.next = None
    return rest
   

head = takeInput()
printLL(head)
reverseLL(head)
printLL(head)
b1zrtrql

b1zrtrql1#

问题出在主代码中:你没有使用reverseLL函数返回的值,也就是 new 头,你应该:

head = reverseLL(head)

相关问题