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

时间:2015-04-01 03:49:38

标签: c data-structures linked-list

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

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

现在您必须复制此LL(仅C代码)

1 个答案:

答案 0 :(得分:1)

我正在提供一个直接的解决方案来按节点复制链表。

假设您有一个这样的链接列表, HEAD - >节点1 - >节点2 - > ... 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;
}