繁体   English   中英

反转链表改变原来的链表

[英]Reversing the linked list changes original linked list

我正在尝试反转链接列表,并且我观察到原始头部也正在更改。 下面是我正在使用的代码:

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

调用 function reverseRecursive并将head更新为head=reverseRecursive(head); 然后打印列表(更新后)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM