例42:C語言實作一個簡單連結清單,它由3個學生資料的結點組成,要求輸出各結點中的資料。
解題思路:讀者在學習這道例題的時候,應該首先分析三個問題。
- 各個結點是怎麼樣構成連結清單的?
- 沒有頭指針head行不行?
- p起什麼作用,沒有它行不行?
源代碼示範:
#include<stdio.h>//頭檔案
struct student //定義學生結構體
{
int num; //學号
float score;//成績
struct student *next;
};
int main()//主函數
{
struct student a,b,c;//定義結構體變量
struct student *head,*point;//定義結構體指針變量
a.num=10101;//學号指派
a.score=89.5;//成績指派
b.num=10103;//學号指派
b.score=90.0;//成績指派
c.num=10107;//學号指派
c.score=85.0;//成績指派
head=&a;//将第1個結點的起始位址賦給頭指針head
a.next=&b;//将第2個結點的起始位址賦給第1個結點的next成員
b.next=&c;//将第3個結點的起始位址賦給第2個結點的next成員
c.next=NULL;//第3個結點的next成員賦給null
point=head;
do //do while循環
{
printf("%ld %5.1f\n",point->num,point->score);//輸出結果
point=point->next;
}
while(point!=NULL);
return 0;//主函數傳回值為0
}
複制
編譯運作結果如下:
10101 89.5
10103 90.0
10107 85.0
--------------------------------
Process exited after 0.04469 seconds with return value 0
請按任意鍵繼續. . .
複制
C語言 | 建立連結清單,輸出各結點中的資料
更多案例可以go公衆号:C語言入門到精通