#include<stdio.h>/*双向循环链表的插入和删除,2009年6月29日王红刚*/ #include<stdlib.h> #include <malloc.h> #define ERROR 0 #define OK 1 typedef char ElemType; typedef struct DNode { ElemType data; struct DNode *prior,*next; }DNode,*DoubleList; void CreateList(DoubleList L)/*通过键盘输入表中元素值,利用尾插法建链表*/ { DNode *r, *s; char c; int flag =1; /*设置一个标志,初值为1,当输入"#"时,flag为0,建表结束*/ L->next=L; L->prior=L; r=L; while(flag) { c=getchar(); if(c!='#') { s=(DNode*)malloc(sizeof(DNode)); s->data=c; r->next=s; s->prior=r; r=s; } else { flag=0; r->next=L; L->prior=r; } } /*while*/ } int DlinkIns(DoubleList L,int i,ElemType e) { DNode *s,*p; int k; p=L; k=0; /*从"头"开始,查找第i-1个结点*/ while(p->next!=L&&k<i) /*表未查完且未查到第i-1个时重复,找到p指向第i个*/ { p=p->next; k=k+1; } /*查找第i-1结点*/ if(p->next == L) /*如当前位置p为空表已找完还未数到第i个,说明插入位置不合理*/ { printf("插入位置不合理!"); return ERROR; } s=(DNode*)malloc(sizeof(DNode)); if (s) { s->data=e; s->prior=p->prior; p->prior->next=s; s->next=p; p->prior=s; return OK; } else return ERROR; } int DlinkDel(DoubleList L,int i) { ElemType e; DNode *p; int k; p=L; k=0; /*从"头"开始,查找第i个结点*/ while(p->next!=L && k<i) /*表未查完且未查到第i个时重复,找到p指向第i个*/ { p=p->next; k=k+1; } if(p->next == L) { return ERROR; } else { e=p->data; p->prior->next=p->next; p->next->prior=p->prior; free(p); return OK; } } void main() { DoubleList l; DNode *p; int i; char e; l=(DNode * )malloc(sizeof(DNode)); printf("请输入双向链表数据!:/n"); CreateList(l); p = l->next; while(p!=l) { printf("%c/n",p->data); p=p->next; } printf("情输入插入位置和元素值:/n"); scanf("%d,%c",&i,&e); getchar(); DlinkIns(l,i,e); printf("插入后的链表为:/n"); p = l->next; while(p!=l) { printf("%c/n",p->data); p=p->next; } printf("请输入删除位置:/n"); scanf("%d",&i); DlinkDel(l,i); printf("删除后的链表为:/n"); p = l->next; while(p!=l) { printf("%c/n",p->data); p=p->next; } }