概述
双链表在单链表的基础上,稍加改动,主要添加一个前驱节点,大体和单链表相似。
代码
结构体、头文件等
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;
}