GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

how to clone each node of given linked list?

input =1->3->6->2 output=1->1->3->3->6->6->2->2

asked Apr 25 by Akshay Jhamb

1 Answer

Step 1. Traverse the given linked list (1->3->6->2)

Step 2. For every node (curr), save its next pointer in another variable(say, curr_next) and create a duplicate node of the current node.

Lets say this duplicate node is temp. Then temp->next = curr-_next; and curr->next = temp. Change pointers like this, the next of current node (of original list) is the duplicate node we created. The next of duplicate node we created is the next of the original linked list current node.

Node * curr = head, curr_next;
while(curr != NULL){
Node * temp = new Node;
temp->data = curr->data;
curr_next = curr->next;
temp->next = curr->next;
curr->next = temp;
curr = curr_next; 
}

Hope this clears.

answered May 5 by ekta1994
...