C语言—通用链表
思考:當一個項目里要使用多種結構體類型的鏈表,例如點菜系統里有人員、菜譜兩種結構體,若要對這兩種鏈表操作,就需要編寫2套鏈表操作代碼,對鏈表的操作有鏈表創建、添加節點、刪除節點、獲取鏈表節點個數、獲取鏈表結點數據、釋放鏈表等,這就會花費我們大量的時間。對于這2種業務,對鏈表的操作是相同的,那能不能編寫一套通用的鏈表操作函數,這2種應用只要調用相應的操作函數即可?面臨這樣的問題,所以有了通用鏈表。
這里寫目錄標題
- 通用鏈表設計
- 通用鏈表基本操作
- 通用鏈表示例
通用鏈表設計
通用鏈表結構體:
struct list {void *Data; //存放數據的地址 struct list *next; }員工信息結構體(Data指向改結構體)
struct staff {int iStaffID;char acName[20];char acPasswd[10]; }那么通用鏈表的數據結構圖可以表示為(頭節點不存儲數據)
通用鏈表基本操作
初始化鏈表
void *List_Init(void *data) {struct list * head;head = (struct list *)malloc(sizeof(struct list));head->data=data;head->next=NULL;return head; }添加鏈表節點(添加到鏈表尾部):
void List_Add(struct list *head,void *data) {struct list *pNode,p1=head;pNode=(struct list *)malloc(sizeof(struct list ));while(p1->next != NULL ){ p1=p1->next; //遍歷鏈表,找到最末尾的節點} p1->next=pNode;pNode->data=data;pNode->next=NULL; }獲取鏈表節點個數:
int LIST_Count(struct list * head) {struct list * p1;int nCount = 0;p1=head->next;while(p1 != NULL){nCount++;p1=p1->next;}return nCount; }獲取鏈表某個節點(返回鏈表節點的data):
void *LIST_GetNode(struct list * head,int index) {struct list * p1;int nCount = 0;p1=head;while(p1->next != NULL){if(nCount == index){return p1->data;}p1=p1->next;nCount++;}return NULL; }刪除鏈表的某個節點
int List_Del(struct list * head,int index) {struct list * p1;struct list * p2; //要刪除結點的臨時結點int nCount = 0;p1=head;while(p1->next != NULL){if(nCount == index){p2 = p1->next;p1->next = p1->next->next;delete p2;}p1=p1->next;nCount++;}return nCount; }釋放鏈表
void *List_Free(struct list *head) {struct list *ptr=head;while(ptr!=NULL){ptr=ptr->next;free(head->data);//先釋放數據存儲的內存空間free(head);//再釋放鏈表節點的內存空間head=ptr;}return head; }通用鏈表示例
#include<stdio.h> #include <stdlib.h> #include <string.h>struct list {void *Data; //存放數據的地址 struct list *next; }; struct staff {int iStaffID;char acName[20];char acPasswd[10]; };void Staff_Print(struct list *head) {struct list *p1=head->next;struct staff *people1;while(p1 != NULL){ people1=(struct staff*)p1->Data;printf("%5d%10s%10s\n",people1->iStaffID,people1->acName,people1->acPasswd);p1=p1->next;} } void List_Add(struct list *head,void *data) {struct list *pNode,*p1=head;pNode=(struct list *)malloc(sizeof(struct list ));while(p1->next != NULL ){ p1=p1->next; } //遍歷鏈表,找到最末尾的節點p1->next=pNode;pNode->Data=data;pNode->next=NULL; } void *List_Init(void *data) {struct list * head;head = (struct list *)malloc(sizeof(struct list));head->Data=data;head->next=NULL;return head; } void main() {struct list *head;struct staff *people1,*people2;//初始化鏈表head=(struct list *)List_Init(NULL);//頭節點不存儲數據,參數為NULLpeople1=(struct staff *)malloc(sizeof(struct staff));people2=(struct staff *)malloc(sizeof(struct staff));people1->iStaffID=1001;strcpy(people1->acName,"張三");strcpy(people1->acPasswd,"123456");people2->iStaffID=1002;strcpy(people2->acName,"李四");strcpy(people2->acPasswd,"123456");//添加鏈表節點List_Add(head,people1);List_Add(head,people2);//員工信息打印函數Staff_Print(head); }運行結果:
1001 張三 1234561002 李四 123456總結
- 上一篇: python学习笔记(四)——流程控制
- 下一篇: C语言—文件基础