在链接列表中插入

时间:2015-02-10 12:57:23

标签: c data-structures linked-list

我正在研究如何在开头插入节点,我看到了这个我无法理解的代码。
我没有得到打印功能。

typedef struct node
{
    int data;
    struct node *next;
} Node;
Node *head;
void insert(int x)
{
    Node *temp=(Node*)malloc(sizeof(Node));   
    temp->data=x;
    temp->next=head;
    head=temp;
}
void print()
{
    Node *temp=head;
    printf("List is:");
    while(temp!=NULL) //Unable to understand this statement as how will the loop terminate?                  
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

3 个答案:

答案 0 :(得分:2)

假设您的链接列表符合

a->b->c->d
|
|
head

所以现在我们使用临时变量

temp = head;

while(temp != NULL)
{
  //Keep moving temp
  printf("%d\n",temp->x);
  temp = temp->next;
}

所以head永远不会被移动,它只是临时指针,当我们到达temp = NULL

时,它会被移动到列表的末尾。
a->b->c->d
|
|
temp = head

temp = temp->next;

    a->b->c->d
    |  |
    |  |
  head temp

重复上述移动,直到temp = NULL在打印完最后一个节点内容时为TRUE,我们执行temp = temp->next;

答案 1 :(得分:0)

C程序需要一个主要功能才能开始。如果你想测试上面的代码,你需要添加一个main函数来在开始时将head初始化为NULL,多次调用insert()并使用print()来检查结果。

答案 2 :(得分:0)

问题上的缩进是一团糟。

但是打印功能是:

  void print() {
      Node *temp=head;             
      printf("List is:");         
      while(temp!=NULL) {         
          printf("%d ",temp->data);
          temp=temp->next;
      }
   }

如果head==NULL,则temp==NULL在开始时,循环将立即终止。

如果head!=NULL开始时temp!=NULL,则会输出head元素的数据。

然后,行temp=temp->next;会使temp指向列表中的下一个Node,循环将前进。 如果仅在列表中的Node上,则循环将终止。

否则它将打印下一个元素的数据,而行temp=temp->next将移至第三个Node(如果有)。

等等......

NB:不建议使用Node *head;行。它将初始化为NULL,因为它具有静态存储持续时间。但Node *head=NULL;建议用于面向未来和可读性。