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;
}
相关推荐
star010-9 分钟前
【视频+图文详解】HTML基础4-html标签的基本使用
前端·windows·经验分享·网络安全·html·html5
engchina14 分钟前
CSS Display属性完全指南
前端·css
engchina18 分钟前
详解CSS `clear` 属性及其各个选项
前端·css·css3
沈韶珺18 分钟前
Elixir语言的安全开发
开发语言·后端·golang
南玖yy1 小时前
C语言:数组的介绍与使用
c语言·开发语言·算法
yashunan1 小时前
Web_php_unserialize
android·前端·php
m0_zj2 小时前
17.[前端开发]Day17-形变-动画-vertical-align
前端·css·chrome·html·html5
码界筑梦坊2 小时前
基于Django的个人博客系统的设计与实现
后端·python·django·毕业设计
Edward-tan2 小时前
【玩转全栈】--创建一个自己的vue项目
前端·javascript·vue.js
青年夏日科技工作者2 小时前
虚幻浏览器插件 UE与JS通信
前端·javascript·html