双向循环链表

本文介绍了一种双向循环链表的数据结构实现方法,并提供了插入、删除等基本操作的C++代码示例。通过该实现可以有效地管理和操作链表中的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.运行结果
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值