麻烦找下错误
#include "stdlib.h "
#include "stdio.h "
struct list
{
int data;
struct list *next;
};
typedef struct list node;
typedef node *link;
void main()
{
link ptr, head,p;
int num=1,i,lent=0;
head=(link)malloc(sizeof(node));
p=ptr=head;
printf( "please input the numbers==> \n ");
while(num> 0)
{ scanf( "%d ",&num);
if(num <=0)
break;
ptr-> data=num;
ptr-> next=(link)malloc(sizeof(node));
ptr=ptr-> next;
lent++;
}
ptr=NULL;
while(p!=NULL)
{printf( "the value is ==> %d\n ",p-> data);
p=p-> next;
}
printf( "the length of the link is %d ",lent);
getch();
}
小弟想建立一个任意长度的链表;输入已 0 结束;但输出结果有点问题麻烦各位看一下,哪里错了
[解决办法]
#include "stdlib.h "
#include "stdio.h "
#include <conio.h>
struct list
{
int data;
struct list *next;
};
typedef struct list node;
typedef node *link;
void main()
{
link ptr, head,p;
int num=1,i,lent=0;
head=(link)malloc(sizeof(node));
p=ptr=head;
ptr=head;
printf( "please input the numbers==> \n ");
while(num> 0)
{
scanf( "%d ",&num);
if(num <=0)
{
free(ptr);//释放上次循环分配的内存,如果第一次循环输入的num就小于0,释放的是head.链表为空.
if(lent==0)
head=NULL;
else
p-> next = NULL;//尾结点的next指向NULL.
break;
}
ptr-> data=num;
ptr-> next=(link)malloc(sizeof(node));
p=ptr; //在ptr指向下一个节点之前,记录下当前节点
ptr=ptr-> next;
lent++;
}
//ptr=NULL;
p=head;
while(p!=NULL )
{
printf( "the value is ==> %d\n ",p-> data);
p=p-> next;
}
printf( "the length of the link is %d\n ",lent);
getch();
}