双向循环链表
来源:互联网 发布:Ubuntu 12 开机启动 编辑:程序博客网 时间:2024/06/08 07:56
1.思路
在双向链表的基础上,让末结点的next指向表头结点,表头结点的pre指向末结点。
2.代码
#include<iostream>using namespace std;struct node { int data; node* pPre; node* pNext;};node* creat() { node* pHead = (node*)malloc(sizeof(node)); pHead->data = 0; pHead->pNext = pHead; pHead->pPre = pHead; return pHead;}bool isempty(node* pHead) { return pHead->pNext == pHead;}void print(node* pHead) { if(pHead == NULL) { cout << "list failed" << endl; return; } if(isempty(pHead)) { cout << "list empty" << endl; return; } node* cur = pHead->pNext; while(cur != pHead) { cout << cur->data << " "; cur = cur->pNext; } cout << endl;}int getlen(node* pHead) { int res = 0; node* tmp = pHead->pNext; while(tmp != pHead) { res++; tmp = tmp->pNext; } return res;}void insert(node* pHead, int pos, int n) { if(pos < 0 || pos > getlen(pHead)) return; node* pNew = (node*)malloc(sizeof(node)); node* tmp = NULL; while(pos--) { pHead = pHead->pNext; } pNew->data = n; tmp = pHead->pNext; pNew->pNext = tmp; tmp->pPre = pNew; pHead->pNext = pNew; pNew->pPre = pHead;}void del(node* pHead, int pos) {//删除操作的形参是结点的位置 if(pos < 0 || pos > getlen(pHead)) return; while(pos--) { pHead = pHead->pNext; } node* tmp = pHead->pNext->pNext; free(pHead->pNext); pHead->pNext = tmp; tmp->pPre = pHead;}void destroy(node* pHead) { while(pHead->pNext != pHead) { node* tmp = pHead->pNext->pNext; free(pHead->pNext); pHead->pNext = NULL; tmp->pPre = pHead; pHead->pNext = tmp; }}int main() { node* p = creat(); insert(p, 0, 1); insert(p, 1, 9); insert(p, 1, 5); insert(p, 1, 7); insert(p, 1, 3); print(p); del(p, 2); print(p); del(p, 0); del(p, 2); print(p); del(p, 0); del(p, 0); print(p); cout << getlen(p) << endl; destroy(p); free(p); p = NULL; print(p); return 0;}
3.运行结果
阅读全文
0 0
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 双向循环链表
- 循环双向链表
- POJ1661Help Jimmy(dp)
- 最近天气变冷了
- PAT乙级1031. 查验身份证(15)
- 微信开发--微信分享自定义图标和标题
- Java多线程系列--【基础篇05】- 线程等待与唤醒
- 双向循环链表
- 数据存储过程之MySQL与ORACLE数据库的差别
- Android下拉刷新框架大集合
- 关于HDFS
- 断言assert()的简介
- project euler 6
- sparkstreaming+kafka
- View的工作原理之measure过程
- 1.2java开发环境搭建