#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct NAME { char *name; struct NAME *pre; struct NAME *nxt; }T_Name,*PT_Name; PT_Name ptNameHead; int ListAllName() { PT_Name ptTemp; int i=0; if(!ptNameHead) { printf("have no name "); return -1; } else { ptTemp=ptNameHead; while(ptTemp) { printf("%06d ,%s ",i++,ptTemp->name); ptTemp=ptTemp->nxt; } } return 0; } void AddName(PT_Name ptNew) { PT_Name ptCur; if(!ptNameHead) { ptNameHead = ptNew; } else {//有数据 ptCur=ptNameHead; while(ptCur->nxt) { ptCur=ptCur->nxt; } ptCur->nxt = ptNew; ptNew->pre = ptCur; } } void AddOneName() { PT_Name ptNew; char name[128]; char *str; printf("please input one name "); scanf("%s",name); str=malloc(strlen(name)+1);//要多分配一个字节的空间来存放字符串结尾标记' '字符 strcpy(str,name); /* name是一个局部变量,用来存放名字, 当这个函数结束的时候,该内存就得释放, 所以我们得单独分配一块内来存放这个name , 下面还得用malloc来分配一个结构体大的内存空间, 记住我们定义结构体的时候不能添加static, 因为定义结构提示不会分配内存空间的, 他定义的只是这种类型,所以我们增加的时候 一定要记得分配内存*/ ptNew= malloc(sizeof(T_Name)); ptNew->name=str; ptNew->pre=NULL; ptNew->nxt=NULL; AddName(ptNew); } PT_Name FindName(char *name) { PT_Name ptCur; if(!ptNameHead) { printf("have no name,can't delete it "); return 0; } else { ptCur=ptNameHead; while(ptCur) { if(strcmp(ptCur->name,name)==0) return ptCur; else ptCur=ptCur->nxt; } } return 0; } int DelName(PT_Name ptDel) { PT_Name ptCur,ptPre,ptNxt; if(ptNameHead==ptDel) { ptNameHead= ptDel->nxt; } else { ptCur=ptNameHead->nxt; while(ptCur) { if(ptCur == ptDel) { ptPre=ptCur->pre; ptNxt=ptCur->nxt; ptPre->nxt=ptNxt; if(ptNxt) { ptNxt->pre=ptPre; } free(ptDel->name); free(ptDel); return 0; } else ptCur=ptCur->nxt; } } return -1; } void DelOneName() { PT_Name ptDel; char name[128]; printf("please input the name you want to delete "); scanf("%s",name); ptDel=FindName(name); if(!ptDel) { printf("can not find the name "); return -1; } DelName(ptDel); } int main(int argc,char **argv) { char c; while(1) { printf("<l> list all the name "); printf("<a> add one name "); printf("<d> delete one name "); printf("<q> quit "); c=getchar(); switch(c) { case 'l': { ListAllName(); break; } case 'a': { AddOneName(); break; } case 'd': { DelOneName(); break; } case 'q': { return 0; break; } default: break; } } return 0; }