A Linked List is a linear data structure in which each node is having two blocks such that one block contains the value or data of the node and the other block contains the address of the next field.
Let us assume that we have a linked list such that each node contains a random pointer which is pointing to other nodes in the list. The task is to construct the list with the same as the original list. Copying the list from the original list which is having some random pointer is called a 'Deep Copy' of the linked list.
For Example
Input-1:
Output:
5-> 2 -> 3 -> 7 ->4 ->
Explanation:
If we append the new list with the value of the original nodes in the given linked list and replace the random pointer of the original linked list with the next node in the new list, then it will become 5-> 2- >3 -> 7-> 4->
We have a linked list with nodes containing its data and a random pointer. To achieve the copy of the linked list with the data and random pointer, we will first append the new node with the same value after each node. This will create a duplicate node after each node.
After initialization, check the path of the random pointer in the list and place the random pointer accordingly into the newly created node.
Now separating the newly created nodes after each node in the original list will create a deep copy of the Linked List.
class listnode: def __init__(self, data): self.data = data self.next = None self.random = None def copyRandomList(head): if head is None: return head # Insert a new node with the same value after each node in the original list. curr = head while curr != None: new = listnode(curr.data) new.next = curr.next curr.next = new curr = curr.next.next # Now place the randompointer with the newly created node. curr = head while curr != None: curr.next.random = curr.random.next curr = curr.next.next # Now Let us separate the newly created list from the original list. curr = head temp = head.next while curr.next != None: dummyHead = curr.next curr.next = curr.next.next curr = dummyHead return temp def printList(head): curr = head while curr != None: print(curr.data, " ", curr.random.data) curr = curr.next head = listnode(1) head.next = listnode(2) head.next.next = listnode(3) head.next.next.next = listnode(4) head.next.next.next.next = listnode(5) head.random = head.next.next head.next.random = head head.next.next.random = head.next.next.next.next head.next.next.next.random = head.next.next.next.next head.next.next.next.next.random = head.next print("Original list:\n") printList(head) copiedList = copyRandomList(head) print("\n Deep Copy of the List:") printList(copiedList)
Running the above code will generate the output as,
Original list: 1 3 2 1 3 5 4 5 5 2 Deep Copy of the List: 1 3 2 1 3 5 4 5 5 2