Ask a Question


Start Coding Today




Data Structures


Interview Experiences

C Programming

C++ Programming

Java Programming



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

+2 votes

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

Please log in or register to answer this question.