问题 您将获得一个(给定:head,最后一个元素->next = NULL)链表,其中 NEXT 指针和 RANDOM 指针作为 LL 节点的属性。
struct node {
node *NEXT;
node *RANDOM;
}
现在您必须复制此 LL(仅限 C 代码)
最佳答案
我给出了一个直接的解决方案来逐个节点复制链表。
假设您有一个像这样的链表,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;
}
关于使用给定的链表创建重复的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29382534/