双向链表(一)

本文介绍了双向链表的基本概念,提供了创建、插入、删除节点的详细步骤,并通过头插法和尾插法展示了如何构建双向链表。此外,还包含了一个测试函数用于验证操作的正确性。双向链表是一种在单链表基础上扩展的数据结构,理解和操作它对于数据结构的学习至关重要。
摘要由CSDN通过智能技术生成

双向链表

在单向链表的基础上拓展的。



前言

双向链表难度不大,在单链表基础上拓展的。


一、基本结构

struct Node {
	int data;
	Node* next;//后继节点
	Node* pre;//前驱节点
};

二、使用步骤

1。创造一个节点

Node* ListCreateNode(int data) {
	Node* node = (Node*)malloc(sizeof(Node));
	node->data = data;
	node->next = NULL;
	node->pre = NULL;
	return node;
}

2.插入节点

Node* ListInsertNode(Node* head, int i, int v) {
	Node* pro, * aft, * vtx;
	int j = 0;
	pro = head;
	while (pro && j < i) {
		pro = pro->next;
		j++;
	}
	if (!pro) {
		return NULL;
	}
	vtx = ListCreateNode(v);
	if (!pro->next) {
		pro->next = vtx;
		vtx->pre = pro;
	}
	else {
		aft = pro->next;
		pro->next = vtx;
		vtx->pre = pro;
		vtx->next = aft;
		aft->pre = vtx;
	}
	return vtx;
}

3.删除节点

Node* ListDeleteNode(Node* head, int i) {
	Node* aft, * pro, * del;
	int j = 0;
	if (!head) {
		return NULL;
	}
	if (i == 0) {//删除头节点
		del = head;
		head = head->next;
		del->next = NULL;
		free(del);
		return head;
	}
	pro = head;
	while (pro && j < i) {
		j++;
		pro = pro->next;
	}
	
	if (!pro && !pro->next) {
		return head;
	}
	//此时要删除pre后面的那个节点
	del = pro->next;
	aft = del->next;
	pro->next = aft;
	aft->pre = pro;
	free(del);
	return head;
}

4.尾插法

Node* ListCreateListByTail(int n, int a[]) {
	Node* head, * tail, * vtx;
	int idx=0;
	if (n <= 0) {
		return NULL;
	}
	vtx = ListCreateNode(a[0]);
	head = tail = vtx;
	while (++idx < n) {
		vtx = ListCreateNode(a[idx]);
		tail->next = vtx;
		vtx->pre = tail;
		tail = vtx;
	}
	return head;
}

5.头插法

Node* ListCreateListByHead(int n, int* a) {
	
	Node* head=ListCreateNode(-1), * vtx;
	
	while (n--) {
		vtx = ListCreateNode(a[n]);
		vtx->next = head;
		head->pre = vtx;//新增
		head = vtx;
	}
	//vtx->next = head;//此处代码是环形链表
	//head->pre = vtx;
	return head;
}

6.测试函数


int main() {
	int a[5] = {4,33,9,8,10};
	Node* head = ListCreateListByHead(5, a);
	ListPrint(head);
	Node* p=ListDeleteNode(head, 2);
	ListInsertNode(head, 3, 999);
	ListPrint(head);
	while (head->next) {
		head = head->next;
	}
	ListPrint2(head->pre);
	
	return 0;
}

总结

双链表会者不难,难者不会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

代码有点萌

谢谢

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

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

打赏作者

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

抵扣说明:

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

余额充值