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

标签 c data-structures linked-list

问题 您将获得一个(给定: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/

相关文章:

c++ - 静态变量在递归中的行为

编译错误 : request for member in something not a structure or union

c - 用户在 C 中输入 int 文件得到 'Access violation'

C - 如果长度不同,则将 2 个字符串中的数字加在一起

c - 面向 C 开发人员的 .vimrc

c++ - udp 选择超时问题。超时或从所有客户端读取

c - 删除堆栈给定索引处的元素,该索引是堆栈链表的一部分

algorithm - 按总和顺序生成子集的算法

不使用指针创建链接列表与使用指针创建链接列表

c++ - 通过指针比较聚合类型的成员值