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

时间:2015-03-29 07:28:00

标签: 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 -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));
}

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

1 个答案:

答案 0 :(得分:0)

当您传入指向create的指针时,它会创建指针的副本。也就是说,如果您在list中修改create,则不会更改listmain的值。

尝试将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**,因为它不会更改列表。