双链表具体操作实现

详细说明:https://blog.youkuaiyun.com/qq_43643944/article/details/114790387

具体代码
#include<iostream>

using namespace std;
typedef struct DNode {
    int data;
    struct DNode *prior, *next;
} *DLinkList;

void InitDLinkList(DLinkList &L) {//初始化双链表
    L = (DNode *) malloc(sizeof(DNode));
    if (L == NULL) {
        cout << "内存分配失败!" << endl;
        return;
    }
    L->prior = NULL;
    L->next = NULL;
}

void createDLinkList(DLinkList &L) {//尾插法建立一个长度为10的双链表
    DNode *r = L;//指向最后一个一个节点
    for (int i = 0; i < 10; i++) {
        DNode *p = (DNode *) malloc(sizeof(DNode));
        p->data = i + 1;
        p->next = r->next;
        p->prior = r;
        r->next = p;
        r = p;
    }

}

DNode *getElem(DLinkList L, int i) {//按序号查找
    DNode *p = L;
    int j = 0;
    if (i < 0)
        return NULL;
    while (p != NULL && j < i) {
        p = p->next;
        j++;
    }
    return p;
}

void inDLinkList(DLinkList &L, int i, int val) {//插入结点
    DNode *p = getElem(L, i);
    if (p == NULL) {
        cout << "插入失败,请检查编号是否有误!" << endl;
        return;
    }
    DNode *q = (DNode *) malloc(sizeof(DNode));
    q->data = val;
    if (p->next == NULL) {//最后一个节点
        q->next = p->next;
        q->prior = p;
        p->next = q;
    } else {
        q->next = p->next;
        q->prior = p;
        p->next->prior = q;
        p->next = q;
    }

}

void deDLinkList(DLinkList &L, int i) {//删除结点
    DNode *p = getElem(L, i);//找到第i个结点
    if (p == NULL || i == 0) {
        cout << "删除失败,请检查编号!" << endl;
        return;
    } else if (p->next == NULL) {//最后一个结点
        p->prior->next = NULL;
        free(p);
    } else {
        p->prior->next = p->next;
        p->next->prior = p->prior;
        free(p);
    }

}

int main() {
    DLinkList L;
    InitDLinkList(L);
    createDLinkList(L);
    cout << "遍历链表:";
    DNode *p = L->next;
    while (p) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
    cout << "插入元素11:";
    inDLinkList(L, 10, 11);
    DNode *p1 = L->next;
    while (p1) {
        cout << p1->data << " ";
        p1 = p1->next;
    }
    cout << endl;
    cout << "删除2:";
    deDLinkList(L, 2);
    DNode *p2 = L->next;
    while (p2) {
        cout << p2->data << " ";
        p2 = p2->next;
    }

    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Missヾaurora

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值