双向循环链表
程序员文章站
2022-05-12 16:33:02
...
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.运行结果
下一篇: 性能优化