首页 > 代码库 > 循环双链表的简单实现
循环双链表的简单实现
<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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。