/*双向循环链表*/ #include "declaration.h" typedef struct DulNode { int data; struct DulNode *next,*prior; }DulNode,*DulLinkList; Status InitList_DUL(DulLinkList &L)//初始化一个带头结点的双向循环链表,ok { L=(DulNode*)malloc(sizeof(DulNode)); L->next=L; L->prior=L; if (!L) exit(OVERFLOW); return OK; } void DestoryList_DUL(DulLinkList &L)//销毁一个带头结点的双向循环链表,ok { DulNode *p; while(L) { p=L->next; free( L); L=p; } } void CreateList_DUL(DulLinkList &L)//正序创建一个带头结点的双向循环链表,ok { DulLinkList p,s;//中间变量 int n,i; printf("input Length: \n"); scanf("%d",&n); p=L; printf("input value with enter:"); for(i=n;i>0;i--) { s=(DulLinkList)malloc(sizeof(DulNode)); scanf("%d",&s->data); p->next=s; s->prior=p; p=s; } p->next=L; L->prior=p; } DulLinkList LocateELem_DUL(DulLinkList L,ElemType x) {//定位值为e的结点的位置 DulNode *p; p=L->next; while(p!=L) { if(!compare(x,p->data)) return p; p=p->next; } printf("the element is not exists\n"); return NULL; } Status InsertAfter_DUL(DulLinkList &L,ElemType y)//在带头结点的双向循环链表中的x值后插入y值,李大友2.15 { DulLinkList p,s; ElemType x; printf("value you want to find is :"); scanf("%d",&x); p=LocateELem_DUL(L,x); if(!p) { printf("%d not exists.\n",x); return ERROR; } s=(DulLinkList)malloc(sizeof(DulNode)); s->data=y; s->next=p->next; p->next->prior=s; p->next=s; s->prior=p; return OK; }//LinkList_L //删除 DulNode* deleteTheNode(DulNode* head,int num) { DulNode* p1,*p2; p1=head; while (p1->next&&num!=p1->data) { p1=p1->next; } if (num==p1->data) { if (p1==head)//找到的是头节点 { head=head->next; head->prior=NULL; } else if(p1->next)//不是头结点,也不是尾节点 { p1->next->prior=p1->prior; p1->prior->next=p1->next; } else { p1->prior->next=NULL; free(p1); } } else { //cout<<"节点未找到"<<endl; printf("节点未找到"); } return head; } //主函数如下 void main() { DulLinkList p; DulLinkList L; InitList_DUL(L); // NCreateList_L(L);//逆位序建立链表 CreateList_DUL(L);//正序建立双向循环链表 ListTraverse_DUL(L); // ListPrint_L(L); // Reverse_DulLinkList(L);//OK // ListTraverse_DUL(L); // ListPrint_DUL(L); ElemType y; printf("the insert value is :"); scanf("%d",&y); // InsertBefore_DUL(L,y);//OK InsertAfter_DUL(L,y); //OK ListTraverse_DUL(L); // ListPrint_DUL(L); ElemType z; printf("the delete value is :"); scanf("%d",&z); deleteTheNode(L,z); ListTraverse_DUL(L); }
删除操作借鉴了:
zz198808 的博客 http://blog.csdn.net/zz198808/article/details/7934427,在此表示感谢
双向链表的初始化,建立,添加节点和删除节点(注意插入和删除要分三种情况)
原文地址:http://blog.csdn.net/fengsuiyingdong/article/details/42150471