記錄下踩的幾個坑
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;
}