Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用递归创建打印和计数链表_C_Linked List - Fatal编程技术网

C 使用递归创建打印和计数链表

C 使用递归创建打印和计数链表,c,linked-list,C,Linked List,我试图创建如下的链表,但输出是一个固定的列表 由两个元素组成,计数为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 -

我试图创建如下的链表,但输出是一个固定的列表 由两个元素组成,计数为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));
}

将指针传递到函数时是否有任何问题。

当传入指针以创建它时,将创建指针的副本。也就是说,如果您在“创建”中修改列表,它将不会更改main中列表的值

尝试在main中传递指向列表的指针以创建。这将允许您在创建中保存列表


打印应该按原样工作。它不需要节点**,因为它不会更改列表。

node*mallocsizeofnode*是错误的人。您需要将其写入node*mallocsizeofnode;感谢您将我的代码更正为头脑风暴和yasir Majeed。如果我在最初分配内存后通过指针,代码似乎可以正常工作,那么为什么会发生这种情况?
// 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 

   // ...

}