C链表复制错误

C链表复制错误,c,linked-list,copy,iteration,C,Linked List,Copy,Iteration,我是C语言的新手,正在复制一个链表。它在while循环中的某个地方出现seg故障,我想我的指针出现了一些问题。此外,我不确定是否需要对每个“下一个”节点进行malloc。是吗?我不得不这样做是有道理的 struct node* copyList() { struct node* walker = head; // starting point to "walk" the list struct node* temp; temp = (struct node*)malloc(size

我是C语言的新手,正在复制一个链表。它在while循环中的某个地方出现seg故障,我想我的指针出现了一些问题。此外,我不确定是否需要对每个“下一个”节点进行malloc。是吗?我不得不这样做是有道理的

struct node* copyList() {
  struct node* walker = head;  // starting point to "walk" the list
  struct node* temp;
  temp = (struct node*)malloc(sizeof(struct node));
  temp->data = walker->data;

  while( walker != NULL ){ // done when we reach the node pointing to NULL
     walker = walker->next;    // advance walker to the next node in the list
     temp = temp->next;
     temp = (struct node*)malloc(sizeof(struct node));
     temp->data = walker->data;
     }
  return walker;
}
节点支柱如下所示

struct node {
    int data;
    struct node* next;
};

您希望循环中
temp->next
的值来自哪里


此外,为了得到更多的元,使用STD:C++中的列表可能会更好,而不是像这样实现自己的数据结构。即使对于经验丰富的工程师来说,这样的工作也是出了名的容易出错。

假设您到达了最后一个节点

现在在循环内部,您递增
walker
。所以现在
walker=NULL

所以这个语句给出了一个错误
temp->data=walker->data

此外,您只是创建节点和复制数据,而不是连接新的链接列表

  • 您需要维护新的头指针以在末尾返回
  • 保留对上一个节点的引用,以便可以将其链接到当前节点
  • 更新指针
  • 按照这句话来改

    struct node* copyList() {
       struct node* walker = head;  // starting point to "walk" the list
       struct node* newHead=NULL,temp,prev=NULL;
    
       while( walker != NULL ){ // done when we reach the node pointing to NULL
         temp = (struct node*)malloc(sizeof(struct node)); //create new node
         temp->data = walker->data;          //copy data
         if(prev==NULL)                      //if its first node
             newHead = temp;                 //new head pointer                  
         else          
             prev->next = temp;              //else link to previous node                  
         prev = temp;                        //update pointers
         walker = walker->next;
       }
       return newHead;
    }
    

    为什么有临时节点?此外,您可能还需要对照
    walker->next!=NULL
    或者至少在循环中检查它是否确实为NULL。