<span style="font-size:18px;"><strong>//代码为自己编写,可能有问题,欢迎大家留言指正!</strong></span>
<span style="font-size:18px;"><strong> </strong></span>
#include <iostream> #include <string> using namespace std; typedef struct dnode { int val; dnode *prior; dnode *next; }dnode; dnode * create(); void traverse(dnode *pHead); bool insert(dnode *pHead,int pos,int val); bool del(dnode *pHead,int pos,int &val); void inverse(dnode *pHead); void main() { dnode *pHead = create(); traverse(pHead); insert(pHead,3,5); traverse(pHead); int val; del(pHead,4,val); cout<<val<<endl; traverse(pHead); inverse(pHead); //traverse(pHead); } //建立循环双链表 dnode *create() { dnode *pHead = new dnode,*pTail; pTail = pHead; pTail->next = pHead; //pHead->prior = pTail; for (int i =0;i<4;i++) { dnode *pNew = new dnode; pNew->val = i+1; pNew->next = pTail->next; pTail->next = pNew; pNew->prior = pTail; pTail = pNew; } pHead->prior = pTail; return pHead; } void traverse(dnode *pHead) { dnode *p =pHead->next; while (p != pHead) { cout<<p->val<<" "; p = p->next; } cout<<endl; } bool insert(dnode *pHead,int pos,int val) { dnode *p = pHead,*q; int i = 1; while (p->next != pHead && i < pos) //找到pos-1个节点(不包括头结点) { ++i; p = p->next; } if (i > pos || p->next == pHead) { return false; } dnode *pNew = new dnode; q = p->next; pNew->val = val; p->next = pNew; pNew->prior = p; pNew->next = q; q->prior = pNew; return true; } bool del(dnode *pHead,int pos,int &val) { dnode *p = pHead,*q; int i = 1; while (p->next != pHead && i < pos) //找到pos-1个节点(不包括头结点) { ++i; p = p->next; } if (i > pos || p->next == pHead) { return false; } q = p->next; //q为要删除的节点 val = q->val; p->next = q->next; q->next->prior = p; delete q; return true; } //逆序输出 void inverse(dnode *pHead) { dnode *p = pHead->prior; //p指向最后一个节点 while (p != pHead) { cout<<p->val<<" "; p = p->prior; } cout<<endl; }
原文:http://blog.csdn.net/yejun556688/article/details/38304153