《双向循环链表插入和删除.docx》由会员分享,可在线阅读,更多相关《双向循环链表插入和删除.docx(4页珍藏版)》请在三一文库上搜索。
1、西安思源学院电信学院双向循环链表的插入和删除作者:rocky Email:#include/*双向循环链表的插入和删除,2009年6月29日王红刚*/#include#include #define ERROR 0#define OK 1typedef char ElemType;typedef struct DNodeElemType data;struct DNode *prior,*next;DNode,*DoubleList;void CreateList(DoubleList L)/*通过键盘输入表中元素值,利用尾插法建链表*/ DNode *r, *s;char c;int fla
2、g =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;elseflag=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-nex
3、t!=L&knext;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
4、; /*从头开始,查找第i个结点*/while(p-next!=L & knext;k=k+1; if(p-next = L) return ERROR;elsee=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(%cn,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(%cn,p-data);p=p-next;printf(请输入删除位置:n);scanf(%d,&i);DlinkDel(l,i);printf(删除后的链表为:n);p = l-next;while(p!=l)printf(%cn,p-data);p=p-next;