反转链接列表会更改原始链接列表

2024-10-03 02:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试反转一个链表,我发现原来的头也在改变。 下面是我正在使用的代码:

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使用了“分配调用”,但为什么在第一个代码中,头部似乎是通过引用传递的,而在第二个代码中是通过值传递的


Tags: 代码noneoutputreturnifdefheadnext