鏈表有兩種實現方案,一是有頭節點,二是無頭節點。node
方案一中有頭節點,指向頭節點的指針叫作頭指針,可是頭節點只是爲了操做統一方便,頭節點的數據域爲空或者存儲鏈表的長度等信息,只有頭節點的鏈表叫作空鏈表。ide
方案二中沒有頭節點,空鏈表的意義爲頭指針指向NULL,ui
方案一源碼指針
// 此頭文件包含鏈表的基本操做 // 類型:單鏈表 #include<stdlib.h> #include<stdio.h> #include<malloc.h> typedef int ElemType; typedef struct linklist { ElemType nodeData; // 數據區域 struct linklist *next; // 指針區域,指向鏈表的下一個節點 } node; // 構造一個空的鏈表 node *InitList() { node *head; head=(node *)malloc(sizeof(node)); head->nodeData=0; // 頭節點中的數據域表示這個鏈表中的長度 head->next=NULL; return head; } // 銷燬線性表 int ClearList(node *head) { node *temp; while(!head) { temp=head; head=head->next; free(temp); } return 0; } // 鏈表判空,爲空返回0,不空返回1 int LinkEmpty(node *head) { return head->next==NULL?0:1; } // 返回鏈表的長度 int ListLength(node *head) { return head->nodeData; } // 取回第i個節點的數據 ElemType GetElem(node *head,int i) { node *temp; temp=head; if(i<0||i>head->nodeData) { printf("Parameter Error"); exit(1); } while(i-->0) { temp=temp->next; } return temp->nodeData; } // 刪除第i個節點 ElemType DeleteElem(node *head,int i) { int ret; node *temp; temp=head; if(i<0||i>head->nodeData) { printf("Parameter Error"); exit(1); } while(i-->0) { temp=temp->next; } ret=temp->nodeData; free(temp); return ret; } // 插入數據元素,head是頭指針,dat是插入的數據,i是插入位置 ListInsert(node *head,ElemType dat,int i) { node *temp,*TMP; TMP=head->next; // 這個變量用於尋找插入位置的前驅節點 temp=(node *)malloc(sizeof(node)); // 這是用於插入的節點 temp->nodeData=dat; if(i<0||i>head->nodeData+1) { printf("Parameter Error"); exit(1); } else if(i==1) { temp->next=head->next; head->next=temp; head->nodeData++; } else { while(--i>1) // 找到要插入位置的前驅節點 { TMP=TMP->next; } temp->next=TMP->next; TMP->next=temp; head->nodeData++; } } int main() { node *head; head=InitList(); ListInsert(head,3,1); printf("%d\n",GetElem(head,1)); }