Python 扭转链表问题
我正在尝试反向链接,这是我的实现:Python 扭转链表问题,python,linked-list,Python,Linked List,我正在尝试反向链接,这是我的实现: import copy # ... def reverse(linked_list): """ Reverse the inputted linked list Args: linked_list(obj): Linked List to be reversed Returns: obj: Reveresed Linked List """ if linked_list.head
import copy
# ...
def reverse(linked_list):
"""
Reverse the inputted linked list
Args:
linked_list(obj): Linked List to be reversed
Returns:
obj: Reveresed Linked List
"""
if linked_list.head is None:
return linked_list
copy_list = copy.copy(linked_list)
current = copy_list.head
while current.next is not None:
new_head = current.next
tail = current.next.next
new_head.next = copy_list.head
current.next = tail
copy_list.head = new_head
return copy_list
考虑到列表是这样填充的:
myList = LinkedList()
for value in [1, 2, 3, 4, 5]:
myList.append(value)
# myList = [1, 2, 3, 4, 5]
所以myList
现在包含:[1,2,3,4,5]
-到目前为止还不错
但我倒过来说:
reversed = reverse(myList)
# reversed = [5, 4, 3, 2, 1]
# myList = [1]
结果是reversed
确实包含一个反向列表[5,4,3,2,1]
,但作为一个副作用,这将myList的内容更改为:[1]
因此,看起来每当我反转列表,而不是使用它的副本时,我也会更改原始列表。
不知道为什么,因为我显式地创建了一个副本copy\u list=copy.copy(linked\u list)
,然后将我的工作建立在它的基础上
如果你能给我提示,我将不胜感激
PS:我知道以前也有人问过类似的问题,但我对一般解决方案不感兴趣,我更感兴趣的是找出我的实现中的错误。
其他类别:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
def __repr__(self):
return str([v for v in self])
我会告诉你简短的答案,
您正在使用具有两个选项的复制库
浅拷贝
深度复制
copy.copy使用浅拷贝,浅拷贝使用按引用传递,在复制的文件中所做的更改也会影响原始文件
copy.deepcopy创建一个新结构,新文件中的更改不会影响该结构
原始的。“复制”创建一个浅复制(不复制包含的对象,如链表节点)。试试“深度复制”吧。太棒了,非常感谢@MichaelButscher。这就解决了问题。