c语言实现双链表(考研笔记)

概述

双链表在单链表的基础上,稍加改动,主要添加一个前驱节点,大体和单链表相似。

代码

结构体、头文件等

c 复制代码
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define true 1
#define false 0
#define bool char
//链表数据类型
typedef int ElementType;
//双链表
typedef struct DNode {
	ElementType data;
	struct DNode* next;
	struct DNode* prior;
} DNode;
bool intDNode(DNode** head);
bool insertNextDNode(DNode* p, DNode* s);
bool deleteDNode(DNode* p);
bool deleteNextDNode(DNode* p);
bool queryStartToEnd(DNode* head);
bool queryEndToStart(DNode* tail);

初始化

c 复制代码
bool intDNode(DNode** head) {
	*head = (DNode*)malloc(sizeof(DNode));
	if (*head == NULL) {
		return false;
	}
	(*head)->data = 0;
	(*head)->next = NULL;
	(*head)->prior = NULL;
	return true;
}

再p节点之后,插入s节点

c 复制代码
bool insertNextDNode(DNode* p, DNode* s) {
	if (p->next) {
		p->next->prior = s;
	}
	s->next = p->next;
	s->prior = p;
	p->next = s;
	return true;
}

删除指定节点p

c 复制代码
bool deleteDNode(DNode* p) {
	if (p->next) {
		p->next->prior = p->prior;
	}
	p->prior->next = p->next;
	free(p);
	return true;
}

删除当前节点的后继节点

c 复制代码
bool deleteNextDNode(DNode* p) {
	DNode* q = p->next;
	if (p == NULL) {
		return false;
	}
	p->next = q->next;
	if (q->next == NULL) {
		return false;
	}
	q->next->prior = p;
	free(q);
	return true;
}

从前往后遍历

c 复制代码
bool queryStartToEnd(DNode* head) {
	DNode* p = head;
	while (p)
	{
		printf("%d", p->data);
		p = p->next;
	}
	return true;
}

从后往前遍历

c 复制代码
bool queryEndToStart(DNode* tail) {
	DNode* p = tail;
	while (p)
	{
		printf("%d", p->data);
		p = p->prior;
	}
	return true;
}
相关推荐
小屁孩大帅-杨一凡13 分钟前
Azure Document Intelligence
后端·python·microsoft·flask·azure
未脱发程序员1 小时前
【前端】每日一道面试题3:如何实现一个基于CSS Grid的12列自适应布局?
前端·css
三天不学习1 小时前
Visual Studio Code 前端项目开发规范合集【推荐插件】
前端·ide·vscode
爱分享的程序猿-Clark1 小时前
【前端分享】CSS实现3种翻页效果类型,附源码!
前端·css
Code哈哈笑2 小时前
【图书管理系统】深度讲解:图书列表展示的后端实现、高内聚低耦合的应用、前端代码讲解
java·前端·数据库·spring boot·后端
无名之逆2 小时前
Hyperlane: Unleash the Power of Rust for High-Performance Web Services
java·开发语言·前端·后端·http·rust·web
数据潜水员2 小时前
`待办事项css样式
前端·css·css3
_处女座程序员的日常2 小时前
css媒体查询及css变量
前端·css·媒体
薯条不要番茄酱2 小时前
【SpringBoot】从环境准备到创建SpringBoot项目的全面解析.
java·spring boot·后端
GanGuaGua4 小时前
CSS:盒子模型
开发语言·前端·css·html