下面是源代码下载连接
下面我也把源代码贴一下,方便大家为我指针正错误,谢谢。。 /* lnklst.h */ #ifndef __LNKLST_H #define __LNKLST_H
#include "lnklst.cpp"
extern struct student *create(char *,int,float,float,float); extern struct student *linear_search(char *); extern void add_stu(struct student *); extern void del_stu(int); extern void insert_stu(struct student *); extern void display_all(void); extern int item_count(void); extern void free_lnklst(void);
#endif /* lnklst.cpp */ #define MAX_NAME 16
/* 学生档案结构 */ struct student { char name[MAX_NAME]; /* 学生姓名 */ int stuid; /* 学生学号 */ float chinese; /* 语文成绩 */ float math; /* 数学成绩 */ float english; /* 英语成绩 */ struct student *prev; /* 链表的前一项 */ struct student *next; /* 链表的后一项 */ };
typedef unsigned char BOOL;
struct student *head; /* 链表表头 */ struct student *curpos; /* 当前指针 */
void display_all(void) { struct student *p=head; if(!p) { printf("The list is empty!\n"); return ; } while(p) { printf("%s,%d,%f,%f,%f\n",p->name,p->stuid,p->chinese,p->math,p->english); p=p->next; } }
struct student *create(char *name,int stuid,float chn,float math,float en) { /* 根据传入的参数,创建一个学生结构体 */ struct student *stu; /* 给声明的结构体指针分配内存 */ stu=(struct student *)malloc(sizeof(struct student)); if(!stu) /* 如果无法分配内存 */ { printf("Cannot allocate memory for structure!\n"); exit(1); /* 强制终止程序 */ } stu->stuid=stuid; strcpy(stu->name,name); stu->chinese=chn; stu->math=math; stu->english=en; return stu; /* 将创建的结构体指针传递给函数 */ }
void add_stu(struct student *stu) { /* 向链表中添加新的结构体 */ if(!head) /* 如果表头为空,则将结构体添加到表头 */ { head=stu; curpos=head; head->next=NULL; /* 后一项无数据,设为NULL */ head->prev=NULL; /* 前一项无数据,设为NULL */ } else { curpos->next=stu; stu->prev=curpos; stu->next=NULL; curpos=curpos->next; } }
struct student *linear_search(char *name) { /* 根据传入的名字,查找相应的记录 */ struct student *stu; stu=head; while(stu) { if(!strcmp(stu->name,name)) return stu; stu=stu->next; } printf("No such student record in the linked list!\n"); return NULL; }
void del_stu(int stuid) { /* 根据学号删除学生 */ struct student *stu; stu=head; while(stu) { if(stu->stuid==stuid) { struct student *bak; if(stu->prev&&stu->next) { bak=stu->prev; bak->next=stu->next; bak=bak->next; bak->prev=stu->prev; } else if(!stu->prev&&stu->next) { head=stu->next; head->prev=NULL; } else if(stu->prev&&!stu->next) { bak=stu->prev; bak->next=NULL; } if(stu->name) free(stu->name); free(stu); } stu=stu->next; } printf("No such student can be removed from the linked list!\n"); }
void insert_stu(struct student *stu) { struct student *p=head,*baknext,*bakprev,*bak; while(p) { baknext=p->next; if(baknext) { if(((stu->stuid)<=(baknext->stuid))&&((stu->stuid)>=(p->stuid))) { stu->prev=p; p->next=stu; baknext->prev=stu; stu->next=baknext; return; } } else add_stu(stu); p=p->next; } }
int item_count(void) { struct student *p=head; int c=0; while(p) { c++; p=p->next; } return c; }
void free_lnklst(void) { /* 释放链表 */ struct student *p=head,*bak; while(p) { bak=p->next; //if(p->name) free(p->name); free(p); p=bak; } }