记录下踩的几个坑
scanf("%d-%s-%d", ... ... ...);
中间的字符串不好区分,会导致输入错误,改成了scanf("%d-%d-%s", ... ... ...);
还是分开输入比较好
CreateList(student **head);
这里用二级指针(一级指针为局部变量),n=CreatList(&head);
struct student *head;
head->no head里面的量.输入要取地址
如:scanf("%d-%d-%s",&p2->no,&p2->score,&p2->name);
- 链表创建有头插和尾插,这里用尾插但是保留头结点位置.
- 代码:
#include <stdio.h>
#include <stdlib.h>
struct student
{
int no;
char name[9];
int score;
struct student *next;
};
int CreateList(student **head)
{
int n;
student *p1,*p2;
int i=0;
printf("number?");
scanf("%d",&n);
if(n<=0) return 0;
else
{
*head=(struct student*)malloc(sizeof(student));
(*head)->next=NULL;
printf("data:%d no-score-name:\n",i+1);
scanf("%d-%d-%s",&(*head)->no,&(*head)->score,&(*head)->name);
p1=*head;
for(i=1;i<n;i++)
{
p2=(struct student*)malloc(sizeof(student));
p2->next=NULL;
p1->next=p2;
p1=p2;
printf("data:%d no-name-score:\n",i+1);
scanf("%d-%d-%s",&p2->no,&p2->score,&p2->name);
}
return n;
}
}
int DestroyList(struct student *head)
{
student *p1,*p2;
p1=head;
p2=p1;
while(p2!=NULL)
{
p2=p1->next;
free(p1);
}
return p2==NULL?1:0;
}
void OutList(student *head)
{
student *p;
p=head;
printf("-----out--------\n");
while(p!=NULL)
{
printf("no:%d name:%s score:%d \n",p->no,p->name,p->score);
p=p->next;
}
}
int main()
{
student *head=NULL;
int n=CreateList(&head);
if(n==0)
{
printf("error!");
return 0;
}
printf("%s",head);
OutList(head);
DestroyList(head);
return 0;
}