先写头文件dlist.h
#pragma once
//双向链表结构体设计:
typedef int ELEM_TYPE;
typedef struct Dlist
{
ELEM_TYPE data;//数据域 保存有效值
struct Dlist* next;//指针域 保存下一个节点的地址(后继)
struct Dlist* prior;//指针域 保存上一个节点的地址(前驱)
}Dlist, *PDlist;
//双向链表可执行函数声明:
//初始化
void Init_dlist(struct Dlist* plist);
//购买新节点
struct Dlist* BuyNode(ELEM_TYPE val);
//头插
bool Insert_head(PDlist plist, ELEM_TYPE val);
//尾插
bool Insert_tail(PDlist plist, ELEM_TYPE val);
//按位置插
bool Insert_pos(PDlist plist, int pos, ELEM_TYPE val);
//头删
bool Del_head(PDlist plist);
//尾删
bool Del_tail(PDlist plist);
//按位置删
bool Del_pos(PDlist plist, int pos);
//按值删除
bool Del_val(PDlist plist, ELEM_TYPE val);
//查找(如果值重复,返回第一次出现的节点地址)
struct Dlist* Search(PDlist plist, ELEM_TYPE val);
//判空
bool IsEmpty(PDlist plist);
//判满(链表不用实现)
//获取有效长度
int Get_length(PDlist plist);
//清空
void Clear(PDlist plist);
//销毁1
void Destroy(PDlist plist);
//销毁2
void Destroy2(PDlist plist);
//打印
void Show(PDlist plist);
再写dlist.cpp文件
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include "dlist.h"
//初始化(排除两个野指针的风险,将其全部赋值为NULL)
void Init_dlist(struct Dlist* plist)
{
//assert
plist->next = plist->prior = NULL;
}
//购买新节点(一次购买一个)
struct Dlist* BuyNode(ELEM_TYPE val)
{
//assert
struct Dlist* pnewnode = (struct Dlist*)malloc(1 * sizeof(struct Dlist));
assert(pnewnode != NULL);
if(NULL == pnewnode)
{
return NULL; //购买失败
}
pnewnode->data = val;
pnewnode->next = pnewnode->prior = NULL;
return pnewnode;
}
//头插
bool Insert_head(PDlist plist, ELEM_TYPE val)
{
//assert plist
//1.购买新节点
struct Dlist* pnewnode = (struct Dlist*)malloc(1 * sizeof(struct Dlist));