1.链表单位再加一个prev指针指向前一个结构体实现双向,
再加多一个哨兵卫头节点避免了头插代码的特殊性
头文件:
#pragma once
#include<stdlib.h>
#include<stdio.h>
//链表单位
typedef int SLTD;
typedef struct SLT
{
SLTD value ;
struct SLT* prev ;
struct SLT* next;
}SLT;
SLT* BuySLT(SLTD x);
void InitSLT(SLT*phead);
void PushbackSLT(SLT*phead,SLTD x);
void PushfrontSLT(SLT*phead,SLTD x);
void PopbackSLT(SLT*phead);
void PopfrontSLT(SLT*phead);
void InsertSLT(SLT*phead, SLT* pos, SLTD x);
void EraseSLT(SLT*phead, SLT* pos);
void Print(SLT* phead);
双向带头链表源代码,注意头插尾插都可以复用插入代码
#include"SLT.h"
SLT* BuySLT(SLTD x)
{
SLT* p = (SLT*)malloc(sizeof(SLT));
if (!p)
{
return NULL;
}
else
{
p->value = x;
return p;
}
}
void InitSLT(SLT*phead)
{
phead->prev = phead;
phead->next = phead;
}
void PushbackSLT(SLT*phead, SLTD x)
{
InsertSLT(phead, phead, x);
/*SLT* nextSLT= BuySLT(x);
SLT* prevSLT= phead->prev;
prevSLT->next = nextSLT;
nextSLT->prev = prevSLT;
nextSLT->next = phead;
phead->prev = nextSLT;*/
}
void PushfrontSLT(SLT* phead, SLTD x)
{
InsertSLT(phead, phead->next, x);
/*SLT* curSLT = BuySLT(x);
SLT* nextSLT = phead->next;
nextSLT->prev = curSLT;
curSLT->next = nextSLT;
curSLT->prev = phead;
phead->next = curSLT;*/
}
void PopbackSLT(SLT* phead)
{
EraseSLT(phead, phead->prev);
/*if (phead->next == phead)
{
return;
}
SLT* prevSLT = phead->prev->prev;
SLT* PopSLT = phead->prev;
prevSLT->next = phead;
phead->prev = prevSLT;
free(PopSLT);
PopSLT = NULL;
return ;*/
}
void PopfrontSLT(SLT* phead)
{
EraseSLT(phead, phead->next);
/*if (phead->next == phead)
{
return ;
}
SLT* PopSLT = phead->next;
SLT* nextSLT = phead->next->next;
phead->next = nextSLT;
nextSLT->prev = PopSLT;
free(PopSLT);
PopSLT = NULL;*/
}
//在pos前插入数据
void InsertSLT(SLT* phead,SLT*pos,SLTD x)
{
SLT* nextSLT = BuySLT(x);
SLT* prevSLT = pos->prev;
prevSLT->next = nextSLT;
nextSLT->prev = prevSLT;
nextSLT->next = pos;
pos->prev = nextSLT;
}
void EraseSLT(SLT* phead,SLT*pos)
{
if (phead->next == phead)
{
return;
}
SLT* nextSLT = pos->next;
SLT* prevSLT = pos->prev;
prevSLT->next = nextSLT;
nextSLT->prev = prevSLT;
free(pos);
pos = NULL;
}
void Print(SLT* phead)
{
SLT* cur = phead;
printf("<<head>>");
while (cur->next != phead)
{
cur = cur->next;
printf("%d>>", cur->value);
}
printf("\n");
}