例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語言入門到精通
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/239695.html
標籤:其他
