JustVirtually
JustVirtually

Reputation: 160

Create duplicate Linked List with given Linked list

Problem You are given a single (given : head, last element->next = NULL) linked list with NEXT pointer and RANDOM pointer as the attribute of LL node.

struct node {
  node *NEXT;
  node *RANDOM;
}

Now you have to duplicate this LL (Only C code)

Upvotes: 0

Views: 175

Answers (1)

Ayan
Ayan

Reputation: 817

I am giving a straight forward solution to copy the linked list node by node.

Let say you have a linked list like this, HEAD -> Node1 -> Node2 -> ... NodeN -> NULL.

struct node * head_dup = NULL; //Create the head of the duplicate linked list.
struct node * tmp1 = head, * tmp2 = head_dup; //tmp1 for traversing the original linked list and tmp2 for building the duplicate linked list.
while( tmp1 != NULL)
{
    tmp2 = malloc(sizeof(struct node)); //Allocate memory for a new node in the duplicate linked list.
    tmp2->RANDOM = malloc(sizeof(struct node)); //Not sure what you are storing here so allocate memory to it and copy the content of it from tmp1.
    *(tmp2->RANDOM) = *(tmp1->RANDOM);
    tmp2->NEXT = NULL; //Assign NULL at next node of the duplicate linked list.
    tmp2 = tmp2->NEXT; //Move both the pointers to point the next node. 
    tmp1 = tmp1->NEXT;
}

Upvotes: 1

Related Questions