![](https://i-blog.csdnimg.cn/blog_migrate/8a2bc596e4624a9c96633f98fcd24a5a.png)
//初始为空的双链表
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LENWORD 11
typedef struct node{
struct node *pfwd;
struct node *pbwd;
char value[LENWORD];
}Node;
char *my_fgets(char *p,int n);//读取输入
void ClearList(Node **plist);//清空链表
int AddList(Node **plist);//添加节点
void ShowList(Node *plist);//显示链表
Node *Search(Node **plist);//12.8.6查找节点
int Remove(Node **plist,Node *pnode);//12.8.6删除节点
int main(){
Node *pdata=NULL;
ClearList(&pdata);
for(;AddList(&pdata)==1;);
if(pdata) ShowList(pdata);
for(;Remove(&pdata,Search(&pdata));ShowList(pdata));
ClearList(&pdata);
return 0;}
//
char *my_fgets(char *p,int n){
char ch=0,*input=NULL,*found=NULL;
if(input=fgets(p,n,stdin))
if(found=strchr(input,10)) *found=0;
else while((ch=getchar())!=EOF&&ch!=10);
return input;}
void ClearList(Node **plist){
for(Node *ptemp=NULL;*plist;){
ptemp=*plist;
*plist=(*plist)->pfwd;
free(ptemp);
}
}
int AddList(Node **plist){
char input[LENWORD]={0};
Node **proot=plist;
fputs("Input the word(EnterQuit):->",stdout);
if(my_fgets(input,LENWORD)&&*input){//输入不为NULL或者Enter
Node *pcall=NULL;
if(!(pcall=(Node *)calloc(1,sizeof(Node)))) return -1;
strncpy(pcall->value,input,LENWORD);//拷贝字符串
for(;(pcall->pfwd=*plist)&&strcmp(input,(*plist)->value)>=0;plist=&(*plist)->pfwd);//查找插入位置
if(*plist){//新项为非末项
pcall->pbwd=(*plist)->pbwd;//退挂钩
(*plist)->pbwd=pcall;//进项退挂钩
}
else{//新项为末项或唯一项
if(*plist!=*proot){//新项为末项
pcall->pbwd=(*proot)->pbwd;//退挂钩
(*proot)->pbwd=pcall;//首项退挂钩
}
else pcall->pbwd=NULL;//新项为唯一项,退挂钩
}
*plist=pcall;//退项进挂钩
}
else return 0;
return 1;}
void ShowList(Node *plist){
char num[LENWORD]={0};//不能在for中创建
for(int i=0;plist;plist=plist->pfwd,i++){
printf("NO.%d:%s\n",i+1,plist->value);
}
}
Node *Search(Node **plist){
char input[LENWORD]={0};
fputs("Input the word(EnterQuit):->",stdout);
if(!my_fgets(input,LENWORD)||!*input) return NULL;//输入为NULL或者Enter
else for(;*plist&&strcmp(input,(*plist)->value);plist=&(*plist)->pfwd);
return *plist;}
int Remove(Node **plist,Node *pnode){
if(!*plist||!pnode) return 0;
Node **proot=plist;
for(;*plist!=pnode;plist=&(*plist)->pfwd);
if(pnode->pfwd) pnode->pfwd->pbwd=pnode->pbwd;//非末项或唯一项,进项退挂钩
else if(!pnode->pfwd&&*proot!=*plist) (*proot)->pbwd=pnode->pbwd;//末项,首项退挂钩
*plist=pnode->pfwd;//退项进挂钩
free(pnode);//清除节点
if(!*proot) return 0;//链表为空
return 1;}