我正在尝试反转一个链表,我发现原来的头也在改变。 下面是我正在使用的代码:
def reverseRecursive(head):
if head == None:
return head
if head.next == None:
return head
newHead = reverseRecursive(head.next)
tail = head.next
tail.next =head
head.next = None
return newHead
#Original list: (1 --> 2 --> 3 --> 4 --> 5 --> None)
printLL(reverseRecursive(head)) #Output: 5 --> 4 --> 3 --> 2 --> 1 --> None
printLL (head) #Output: 1 --> None
我已经通过撤销链接列表的深层副本来纠正了这个问题,但我面临的问题是 另一个问题是,我将原始头部作为一个论据传递并操纵它,原始头部没有离开它的位置。见下面的代码:
def printLL(head):
while head is not None:
print(str(head.data) + " --> ", end="")
head = head.next
print("None")
#call
head = takeInput()
printLL(head) #Output:1 --> 2 --> 3 --> 4 --> 5 --> None
printLL(head) #Output:1 --> 2 --> 3 --> 4 --> 5 --> None
我知道python使用了“分配调用”,但为什么在第一个代码中,头部似乎是通过引用传递的,而在第二个代码中是通过值传递的
调用函数
reverseRecursive
并将head
更新为head=reverseRecursive(head);
,然后打印列表(更新后)相关问题 更多 >
编程相关推荐