0

我已经编写了一个代码来附加节点是否为空。我认为我的代码和逻辑是正确的,但我仍然无法得到任何答案。它的编译但运行后没有显示任何结果。请告诉我为什么

#include<stdio.h>
#include<stdlib.h>

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

void append(struct node *,int);
void display(struct node*);

void append( struct node *q, int num )
{
    struct node *temp,*r;
    if(q == NULL)
    {
        temp = (struct node*)malloc(sizeof(struct node));
        temp -> data = num;
        temp -> nxt = NULL;
        q = temp;
    }
    else
    {
        temp = q;
        while(temp->nxt != NULL)
        {
            temp = temp->nxt;
        }
        r = (struct node*)malloc(sizeof(struct node));
        r -> data = num;
        r -> nxt = NULL;
        temp->nxt = r;
    }
}

void display(struct node *q)
{
    while(q != NULL)
    {
        printf("%d",q->data);
        q = q->nxt;
    }
}


int main()
{
    struct node *a;
    a= NULL;
    append(a,10);
    append(a,11);
    append(a,12);
    display(a);
    return 0;
}
4

2 回答 2

1

您需要通过地址将第一个参数(列表头)的append地址传递给方法。如所写,它在第一次调用(以及每个后续调用)中传递 NULL,因为它是按值传递的。

原型应该是这样的:

void append( struct node **q, int num )

然后像这样拨打电话:

append(&a,10);

请注意,append需要相应地更新函数以正确处理参数更改。

于 2012-06-09T16:09:31.113 回答
1

append 的原型需要修改为

void append( struct node **q, int num );

并将aas的地址传递&a给此函数。这是因为 C 只支持按值传递。在此处了解更多信息。

请找到修改后的附加功能,如下所示:

void append( struct node **q, int num ) 
{     
  struct node *temp,*r;     

  if(*q == NULL)     
  {         
     temp = (struct node*)malloc(sizeof(struct node));
     temp -> data = num;
     temp -> nxt = NULL;
     *q = temp;
  }
  else
  {
     temp = *q;
     while(temp->nxt != NULL)
     {
         temp = temp->nxt;
     }
     r = (struct node*)malloc(sizeof(struct node));
     r -> data = num;
     r -> nxt = NULL;
     temp->nxt = r;
 } 
} 

此外:

更改以下行:

printf("%d",q->data); 

作为

printf("%d\n",q->data); 

除非某些终端中有换行符,否则 printf 可能不会刷新数据。

于 2012-06-09T16:10:22.427 回答