数据结构(双链表

发布于:2024-04-20 ⋅ 阅读:(32) ⋅ 点赞:(0)

1. 讲解:

在这里插入图片描述

2. C++代码实现:

#include <stdlib.h>
#include <iostream>
#include <stdio.h>

using namespace std;

#define ElemType int

typedef struct DLNode {
	ElemType data;
	struct DLNode *prior, *next;
}DLNode, * DLinkList;

// 判断空
bool Empty(DLinkList L) {
	if (L->next == NULL) return true;
	else return false;
}

// 给定节点后插入节点
bool InsertNextDLNode(DLNode* p, DLNode* s) {
	if (p == NULL || s == NULL) return false;

	s->next = p->next;
	if (p->next != NULL) {
		p->next->prior = s;
	}
	p->next = s;
	s->prior = p;
	return true;
}

// 给定节点前插入节点
bool InsertPriorDLNode(DLNode* p, DLNode* s) {
	return InsertNextDLNode(p->prior, s);
}

// 删除给定节点的后继节点
bool DeleteNextDLNode(DLNode* p) {
	if (p == NULL) return false;
	DLNode* q = p->next;
	if (q == NULL) return false;

	p->next = q->next;
	if (q->next != NULL) {
		q->next->prior = p;
	}
	free(q);
	
	return true;
}

// 销毁
void DestoryList(DLinkList& L) {
	while (L->next != NULL) {
		DeleteNextDLNode(L);
	}
	free(L);
	L = NULL;
}

int main() {
    DLinkList L;

    // 初始化双向链表
    L = (DLNode*)malloc(sizeof(DLNode));
    L->next = NULL;
    L->prior = NULL;

    // 插入节点示例
    DLNode* node1 = (DLNode*)malloc(sizeof(DLNode));
    node1->data = 1;
    InsertNextDLNode(L, node1); // 在头节点后插入node1

    DLNode* node2 = (DLNode*)malloc(sizeof(DLNode));
    node2->data = 2;
    InsertNextDLNode(node1, node2); // 在node1后插入node2

    DLNode* node3 = (DLNode*)malloc(sizeof(DLNode));
    node3->data = 3;
    InsertNextDLNode(node2, node3); // 在node2后插入node3

    // 打印双向链表内容
    DLNode* temp = L->next; // 跳过头节点
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;

    // 删除节点示例
    DeleteNextDLNode(node1); // 删除node1后的节点

    // 再次打印双向链表内容
    temp = L->next; // 重新跳过头节点
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;

    // 销毁双向链表
    DestoryList(L);

    return 0;
}

小结:

关注我给大家分享更多有趣的知识,以下是个人公众号,提供 ||代码兼职|| ||代码问题求解||
添加我的公众号即可: