#ifndef EMPLOYEE_H_INCLUDED #define EMPLOYEE_H_INCLUDED typedef struct employee{ unsigned int primary;//主鍵 unsigned char age;//年齡 char department[32];//部門名稱 char name[15];//員工姓名 char mobile[12];//員工手機號 struct employee * next;//下一條記錄 }EMPLOYEE,*PT_EMPLOYEE; #endif // EMPLOYEE_H_INCLUDED
頭文件,結構體的定義node
#include <stdio.h> #include <stdlib.h> #include "employee.h" /*頭插入法建表*/ PT_EMPLOYEE insert_node(PT_EMPLOYEE head_node,PT_EMPLOYEE new_node) { if(head_node) { new_node->next=head_node; } head_node=new_node; return head_node; } /*按主鍵鍵刪除節點*/ PT_EMPLOYEE remove_node(PT_EMPLOYEE head_node,int primary_value){ PT_EMPLOYEE iterator=head_node; PT_EMPLOYEE temp=0; if(head_node->primaty==primary_value) { printf("%d\n\n\n\n\n\n\n",head_node->primaty); head_node=iterator->next; free(iterator); } else { while(iterator&&iterator->next){ temp=iterator->next; if((temp->primaty)==primary_value) { printf("%d\n\n\n\n\n\n\n",temp->primaty); iterator->next=temp->next; free(temp); break; } else{ iterator=iterator->next; } } } return head_node; } /*計算節點個數*/ int count_node(PT_EMPLOYEE head) { PT_EMPLOYEE iterator=head; int i=0; while(iterator){ ++i; iterator=iterator->next; } return i; } /*打印單鏈表所有內容*/ int show_list(PT_EMPLOYEE head_node) { PT_EMPLOYEE iterator=head_node; while(iterator){ printf("員工工號:%d\n",iterator->primaty); printf("員工姓名:%s\n",iterator->name); printf("部門名稱:%s\n",iterator->department); printf("員工年齡:%d\n",iterator->age); printf("手機號碼: %s\n\n",iterator->mobile); iterator=iterator->next; } return 0; } /*清除全部節點*/ PT_EMPLOYEE clean_list(PT_EMPLOYEE head) { PT_EMPLOYEE iterator=head; while(iterator){ head=head->next; free(iterator); iterator=head; } return head; } /*主函數*/ int main(void) { PT_EMPLOYEE emlist=0; PT_EMPLOYEE new_node=0; int i=1,count=0; for(i=1;i<10;++i){ new_node=malloc(sizeof(EMPLOYEE)); new_node->age=i; new_node->primaty=i; sprintf(new_node->department,"%s%d","部門",i); sprintf(new_node->name,"%s%d","員工",i); sprintf(new_node->mobile,"%s","88888888888"); new_node->next=0; emlist=insert_node(emlist,new_node); } emlist=remove_node(emlist,5); emlist=remove_node(emlist,1); emlist=remove_node(emlist,9); emlist=remove_node(emlist,6); count=count_node(emlist); printf("鏈表長度:%d\n",count); show_list(emlist); emlist=clean_list(emlist); printf("清空之後"); show_list(emlist); return 0; }
主要邏輯實現函數