//用指針處理鏈表
//建立一個簡單的鏈表,它由3個學生數據的結點組成,要求輸出各結點中的數據
/*#include <stdio.h>
struct Student
{
int num;
float score;
struct Student *next;
};
int main()
{
struct Student a,b,c,*head,*p;
a.num = 10101;
a.score = 89.5;
b.num = 10103;
b.score = 90;
c.num = 10107;
c.score = 85;
head = &a; //將結點a的起始地址賦給頭指針head
a.next = &b; //將結點b的起始地址賦給a結點的next成員
b.next = &c; //將結點c的起始地址賦給b結點的next成員
c.next = NULL; //將結點c的next成員不存放其他結點地址
p = head; //使p也指向a結點
do
{
printf("%1d%5.1f\n",p->num,p->score);
p = p->next; //使p指向下一結點
}while(p != NULL); //輸出完c結點後p的值爲NULL,循環終止
return 0;
}*/
//寫一函數建立一個有3名學生數據的單向動態鏈表
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n;
struct Student * creat(void)
{
struct Student * head;
struct Student *p1,*p2;
n = 0;
p1 = p2 = (struct Student *)malloc(LEN); //開闢一個新單元
scanf("%ld,%f",&p1->num,&p1->score); //輸入第1個學生的學號和成績
head = NULL;
while(p1->num != 0)
{
n = n+1;
if(n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct Student *)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
p1->next = NULL;
return (head);
}
int main()
{
struct Student *pt;
pt = creat();
printf("\nnum:%ld\nscore:%5.1f\n",pt->num,pt->score);
return 0;
}
用指針處理鏈表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.