節點
節點主要由以下兩塊組成:
- 數據
- 指向下一個節點的指針
鏈表
鏈表主要由以下幾塊組成:
- 一系列節點
每個節點至少包括:
一條數據(任意類型)
一個該節點類型的指針
節點之間首尾相連(指向鏈表中下一個節點的指針) - 頭指針:指向第一個節點的指針
- 尾節點:節點指針指向空
上圖表示一個4個節點組成的鏈表,鏈表是由一系列的節點, 頭指針(head)與尾節點(即最後一個next指向空);每個節點由data(數據)和next(指向下一個節點的指針)組成.
創建鏈表
創建鏈表主要涉及下面的幾步:
1. 創建節點
2. 鏈:使每個節點的指針域存儲後繼節點的地址
3. 頭:確定頭文件(head)
4. 尾:確定尾節點
/*創建鏈表,輸入學生的個數以及對應的學號與分數.*/
#include <stdio.h>
#include <stdlib.h>
typedef struct student{
long num;
float score;
struct student *next;
}STU;
STU *creat(int n)
{
/*head node*/
STU *Pt, *prePt, *head; //head爲頭指針,Pt爲指針變量
Pt = (STU *)malloc(sizeof(STU)); //申請一塊空間,把這個地址返回到指針變量Pt中.
if (Pt!=NULL) //申請成功
{
scanf("%ld,%f", &Pt->num, &Pt->score);
/*確定頭節點*/
head = Pt; //確定Pt爲頭指針
prePt = Pt; //prePt用來保存鏈表當前的尾節點的地址,在此,頭結點既是頭結點又是尾節點.
}
else
{
printf("Failed.\n");
exit(0);
}
/*other node*/
int i;
for (i=1; i<n; i++)
{
Pt = (STU *)malloc(sizeof(STU));
if (Pt!=NULL)
{
scanf("%ld,%f", &Pt->num, &Pt->score);
prePt->next = Pt;//prePt->next存儲新的節點的地址,即Pt.(當前鏈表的尾節點爲prePt)
prePt = Pt;//prePt存儲的都是當前鏈表的尾節點地址
}
else
{
printf("Failed.\n");
exit(0);
}
}
/*鏈表尾節點指針域爲空*/
Pt->next = NULL; //判斷尾節點
return head;
}
void main()
{
printf("Please the number of students:");
int num;
scanf("%d", &num);
creat(num);
}