使用给定的链接列表创建重复的链接列表

时间:2021-03-29 07:16:47

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.

问题给定一个(给定:head,last element-> next = NULL)链接列表,其中NEXT指针和RANDOM指针作为LL节点的属性。

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

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

现在你必须复制这个LL(只有C代码)

1 个解决方案

#1


1  

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.

假设你有一个像这样的链表,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;
}

#1


1  

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.

假设你有一个像这样的链表,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;
}