我尝试按如下方式创建链接列表,但输出是固定列表 两个元素,并计为2
#include<stdio.h>
#define null 0
struct list
{
int num;
struct list *next;
};
typedef struct list node;
int create(node *list)
{ int n;
printf("enter the element to end the list finish it with -999\n");
scanf("%d",&n);
if(n==-999)return 0;
else {
list=(node *)malloc(sizeof(node *));
list->num=n;
if(!(create(list->next)))list->next=null;
return 1}
}
void printlist(node * list) {
if(list->next==null)
{printf("%d->",list->num);return;}
else
{printf("%d->",list->num);printlist(list->next);}
return;
}
int count(node *list) {
if(list->next==null)return 1;
else return(1+count(list->next));
}
void main() {
node *list;
create(list);
printlist(list);
printf("\n%d",count(list));
}
将指针传递给函数是否有任何问题。
答案 0 :(得分:0)
当您传入指向create
的指针时,它会创建指针的副本。也就是说,如果您在list
中修改create
,则不会更改list
中main
的值。
尝试将list
中的main
指针传递给create
。这样您就可以在create
内添加列表。
// in main:
create(&list)
// in create
int create(node** listptr) {
// similar code to before except
// that list should be replaced with
// (*listptr)
//
// the example below will assing a value
// to the variable list in main:
// (*listptr) = x
// ...
}
打印应该按原样运行。它不需要node**
,因为它不会更改列表。