Python中链表的深拷贝(Deep Copy)实现

2023-04-11 00:00:00 python 链表 拷贝

链表的深拷贝(Deep Copy)意味着创建一个新的链表,其中包含原始链表中所有节点的副本。在Python中,可以使用copy模块中的deepcopy()方法来实现链表的深拷贝。下面是详细的代码演示:

import copy

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 创建原始链表
head = ListNode(1)
node1 = ListNode(2)
node2 = ListNode(3)
node3 = ListNode(4)
head.next = node1
node1.next = node2
node2.next = node3

# 深拷贝链表
new_head = copy.deepcopy(head)

# 修改原始链表的值
head.val = 5

# 输出原始链表的值
print("原始链表的值为:", end="")
curr = head
while curr is not None:
    print(curr.val, end=" ")
    curr = curr.next

# 输出新链表的值
print("\n新链表的值为:", end="")
curr = new_head
while curr is not None:
    print(curr.val, end=" ")
    curr = curr.next

输出结果:

原始链表的值为:5 2 3 4 
新链表的值为:1 2 3 4 

可以看到,原始链表的值已经被修改,但是新链表的值没有受到影响。这说明链表的深拷贝已经成功实现。

相关文章