使用append在C中复制链接列表

时间:2017-03-24 23:51:55

标签: c linked-list

struct node* copyList()
{ 
  //check if empty
  if(head==NULL){
  return NULL;}
  //create head
  struct node* p_head=head;//pointer to original head 
  struct node* newHead = NULL; //head of new list
  struct node* p_newHead=newHead;//pointer to new head
  while(p_head!=NULL)
    int data=p_head->data;
    m_appendNode(data, p_newHead);
    p_head=p_head->next;
  }
  return newHead;
}

当我运行程序时,我的头仍然是null而不是构建列表。请让我知道我错过了什么。 感谢

编辑: 附加功能

void m_appendNode(int data, struct node *newHead)
    {
    struct node* current=newHead;
    if(newHead!=NULL){
      while((current->next)!=NULL){
       current = current->next;
      }
      current->next=malloc(sizeof(struct node));
      current->next->data=data;
      current->next->next=NULL;
      }
    else{
      struct node* newnode=malloc(sizeof(struct node));
      newnode->data=data;
      newHead=newnode;
      newnode->next=NULL;
      }
    }

1 个答案:

答案 0 :(得分:0)

首先,我假设应该有一个' {'在copyList之后。

接下来,您必须了解您作为参数传递给C函数的值会发生什么。发生的是函数复制参数,并将它们视为局部变量,在函数结束后会被遗忘。

琐碎的例子是

void foo ( int a )
{
     a=10;
}
void bar ( void )
{
     int b = 1;
     foo ( b );
}

在调用foo后的bar中,复制了b(即1)的值,foo将其更改为10然后返回到bar,其中b仍未触及且值为1.

你可以做的是将指针传递给该函数。在我们的例子中:

void foo ( int * a )
{
     *a=10;
}
void bar ( void )
{
     int b = 1;
     foo ( &b );
}

在条形结束时,b确实值为10.

现在让我们来看看你的代码,你基本上做同样的事情,你将指向newHead的指针传递给m_appendNode并期望它改变。在我看来,你有两个选择,要么指针指向一个指针(即struct node ** newHead)并在任何地方添加很多星号,要么让函数返回struct node *并将其称为newHead = m_appendNode(data, p_newHead); }。

后者更简单,但我建议您尽量使用第一个选项以获得更好的指针。