【问题标题】:Create duplicate Linked List with given Linked list使用给定的链接列表创建重复的链接列表
【发布时间】:2015-06-05 14:42:11
【问题描述】:

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

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

现在你必须复制这个 LL(仅限 C 代码)

【问题讨论】:

  • 这是作业题吗?您为什么不向我们展示一些您尝试过的代码,并告诉我们您遇到了哪些问题。
  • 不是作业,但我只是在阅读一些在线帖子并试图获得有效的答案。我试图在两个原始节点 Original LL 之间插入新节点: Head -> n1 -> n2 -> ... newHead -> head -> new1 -> n1 -> new2 -> n2 .... 然后只是捕获 New节点也应对 RANDOM 链接。我想知道是否有人有更好的想法来轻松完成它。

标签: c data-structures linked-list


【解决方案1】:

我给出了一个直接的解决方案来逐个节点地复制链表。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多