頭結點是首節點前面的那個節點。
頭結點不存放有效數據,
設置頭結點是爲了方便對鏈表的操作
頭指針:存放頭結點地址的指針變量
首節點:存放第一個有效數據的節點
尾節點:存放最後一個有效數據的節點
確定一個鏈表只需要一個參數:頭指針
#include <stdio.h>
#include <stdlib.h>
//定義一個節點數據類型
struct Node *createList(void);
void traverseList(struct Node*);
//函數聲明
struct Node{
int data;//數據域
struct Node * pNext;
//指針域 ,指向的仍然是一個Node類型數據遞歸知識
};
int main(void){
struct Node *pHead;//pHead用來存放頭結點的指針。注意是頭結點,不是首節點。
pHead = createList();//createList()函數功能:創建一個非循環鏈表 ,pHead就指向了一個有效鏈表。
traverseList(pHead);//遍歷數據
return 0;
}
struct Node *createList(void){
int len,i,val;//鏈表的長度 ,循環變量 ,每個節點的值
struct Node * pHead = (struct Node *)malloc(sizeof(struct Node));//創建一個頭結點
if(pHead == NULL){
printf("分配失敗,程序終止\n");
exit(-1);
}
struct Node * pTail = pHead;//尾節點的指針
pTail->data = NULL ;
printf("請輸入鏈表的長度:");
scanf("%d",&len);
for(i=0;i<len;i++){
printf("請輸入第%d個元素:",i+1);
scanf("%d",&val);
struct Node *pNew =(struct Node *)malloc(sizeof(Node));//每循環一次創建一個新的節點
pNew->data = val;
pTail->pNext =pNew;
pNew->pNext =NULL;
pTail = pNew;
}
printf("\n");
return pHead;
}//用來創建一個非循環鏈表
void traverseList(struct Node* pHead){//遍歷鏈表
/*if(pHead ==NUll){
printf("該鏈表爲空。");
}*/
printf("鏈表數據爲:\n");
struct Node *p = pHead->pNext;
while(p !=NULL){
printf("%d\t",p->data);
p=p->pNext;
}
return;
}