要实现这个问题,需要使用循环来遍历链表并复制每个节点。具体步骤如下:
下面是实现这个算法的Python代码:
class Node: def init(self, data): self.data = data self.next = None
def copy_linked_list(head): if not head: return head
# Create a new empty linked list to store the copied nodes
new_head = Node(head.data)
new_ptr = new_head
# Define the pointers to traverse the linked lists
curr_ptr = head.next
# Loop through the original linked list
while curr_ptr:
# Copy the current node and add it to the new linked list
new_ptr.next = Node(curr_ptr.data)
# Move the pointers to the next nodes
curr_ptr = curr_ptr.next
new_ptr = new_ptr.next
return new_head
使用这个函数,可以复制一个链表并返回复制后的链表的头节点,如下所示:
head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4)
new_head = copy_linked_list(head)
while new_head: print(new_head.data) new_head = new_head.next
输出结果为: 1 2 3 4