一个创建链表的程序,研究了一天还是没运行成功,希望高手们帮忙看一下,谢谢啦
#include<stdio.h>
#include<malloc.h>
struct lianbiao
{
int data;
struct lianbiao *next;
} ;
void initlist(int n)
{
struct lianbiao biao1,*biao;
biao=&biao1;
int i=0;
for(i=0;i<n;i++)
{
biao->next=(lianbiao*)malloc(sizeof(lianbiao));
printf("input\n");
(*(biao->next)).data=scanf("%d\n",(*(biao->next)).data);
printf("suceed\n");
biao=biao->next;
}
}
void main()
{
initlist(5);
}
运行输入数字后,按回车就立马停止工作。额。。 不知道是哪里出了问题呢 望高手指点一下啊
[解决办法]
scanf("%d\n",(*(biao->next)).data); scanf里面不要 ‘\n’
[解决办法]
我写给你吧
#include <stdio.h>
#include <malloc.h>
struct lianbiao {
int data;
struct lianbiao *next;
};
void initlist(struct lianbiao *biao, int n)
{
struct lianbiao *tail = NULL, *new = NULL;
int i;
int num;
for(i = 0; i < n; i++)
{
new = (struct lianbiao *)malloc(sizeof(struct lianbiao));
printf("input: ");
scanf("%d", &num);
new->data = num;
new->next = NULL;
for(tail = biao; tail->next != NULL; tail = tail->next)
;
tail->next = new;
}
}
void show(struct lianbiao *biao)
{
struct lianbiao *tail = NULL;
for(tail = biao->next; tail != NULL; tail = tail->next)
{
printf("data = %d\n", tail->data);
}
}
void destroy(struct lianbiao *biao)
{
struct lianbiao *tail = NULL, *save = NULL;
for(tail = biao->next; tail != NULL; tail = save)
{
save = tail->next;
free(tail);
}
}
int main(void)
{
struct lianbiao biao = {.next = NULL};
initlist(&biao, 5);
show(&biao);
destroy(&biao);
return 0;
}
我的异常网推荐解决方案:程序员的一天,http://www.myexception.cn/other/1391144.html