输入学生信息,然后组织成单向链表,当检测到0时停止
首先是主函数和声明什么的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *head, *tail;
void input();
int main()
{
struct stud_node *p;
head = tail = NULL;
input();
for ( p = head; p != NULL; p = p->next )
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
然后是input函数,建立链表
可以这么搞:
void input()
{
struct stud_node *p;
int number;
scanf("%d",&number);//先判断是否为0
while(number!=0){
p=(struct stud_node*)malloc(sizeof(struct stud_node));
p->num=number;
scanf("%s%d",p->name,&p->score);
p->next=NULL;
if(head==NULL){
head=p;
}else{
tail->next = p;//将p链接到结尾
}
tail=p;
scanf("%d",&number);
}
}
当然也可以这样,其实差不多
可能这种看起来更整齐?
void input()
{
tail=head=NULL;
int number;
scanf("%d", &number);
do{
struct stud_node *a = (struct stud_node *)malloc( sizeof(struct stud_node) );
scanf("%s%d", &a->name, &a->score);
a->next=NULL;
a->num=number;
tail=head;
if(tail!=NULL){
while(tail->next!=NULL)
tail=tail->next;
tail->next=a;
}
else{
head=a;
}
//printf("%d%s%d\n", a->num, a->name, a->score); 这个是个检验
scanf("%d", &number);
}while(number!=0);
return;
}
反正都要注意scanf和外层那个循环的控制
刚开始弄不对就怎么都scan循环不起来!!!
(手撕键盘