我正在使用递归来反转链表,但是没有得到结果。每当我对输入[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)
1条答案
按热度按时间b1zrtrql1#
问题出在主代码中:你没有使用
reverseLL
函数返回的值,也就是 new 头,你应该: