双向循环链表(带头结点)的创建,一共五步,如图所示:
p->next =q; q->prior=p; q->next=head; head->prior =q; p=q;
插入结点操作:
s->prior=p->prior; p->prior->next=s; s->next=p; p->prior=s;
删除结点操作(相对简单,图示略)
p->prior->next=p->next; p->next->prior=p->prior; free(p);
/*--------------------完整代码--------@映雪------------------------*/ #include <iostream> using namespace std; typedef int status; //双向循环链表的存储结构 typedef struct Node { int data; int Length;/*表的长度*/ struct Node *prior;/*前驱*/ struct Node *next;/*后继*/ }Node,*List; /*-------------------初始化-------------------*/ void InitList(List &L) { L=(Node *)malloc(sizeof(Node)); if(L) { L->next=L->prior=L; L->Length=0; } else exit(-1); } /*-------------------创建链表-------------------*/ void Create(List &L,int n) { //输入n个元素的值,建立带头结点的双线循环链表L List p=L,q; int i; for(i=1;i<=n;i++) { q=(List)malloc(sizeof(Node)); cout<<"您该输入第"<<i<<"个元素的值了:"; cin>>q->data; p->next =q; q->prior=p; q->next=L; L->prior =q; p=q; L->Length ++; } } /*-------------------返回第i个元素的指针-------------------*/ List GetElem(List &L,int i) { int j; List p=L->next; for(j=1;j<i;j++)/*第i个元素,移动i-1次*/ p=p->next; return p; } /*-------------------第i个元素位置处插入元素-------------------*/ void InsertList(List &L,int i,int e) { List p,q; p=GetElem(L,i);/*得到第i个元素的指针*/ q=(List)malloc(sizeof(Node)); q->data=e; q->prior=p->prior; p->prior->next=q; q->next=p; p->prior=q; L->Length++; } /*-------------------删除第i个元素-------------------*/ void DeleteList(List &L,int i) { List p; p=GetElem(L,i);/*得到第i个元素的指针*/ p->prior->next=p->next; p->next->prior=p->prior; L->Length --; free(p); } /*-------------------遍历打印-------------------*/ void Display( List &L) /*遍历*/ { List p=L->next;/*指向第一个节点数据*/ cout<<"双向循环链表中的结点的数据为:"<<endl; do { cout<<p->data<<" "; p=p->next ; }while((p->next)!=L); cout<<p->data; } /*-------------------销毁链表-------------------*/ void DestoryList(List &L) { List p,q; p=L->next; while(p!=L) { q=p; p=p->next; free(q); }; L->next=L; L->prior=L; L->Length=0; } int main() { List L; int n; InitList(L) ; cout<<"创建几个循环节点,请输入:"; cin>>n; Create(L,n);/*创建*/ Display(L); InsertList(L,3,500);/*插入*/ Display(L); DeleteList(L,1);/*删除*/ Display(L); DestoryList(L);/*销毁*/ cout<<L->next->Length; return 0; }