#include "dblist.h"
//创建一个双向链表
//将26个英文字母通过头插的方式插入到链表中
//通过尾删的方式将数据读取出来并删除
//创建头结点
pdblist create_head()
{
pdblist H = (pdblist)malloc(sizeof(Node));
if(H == NULL)
{
printf("申请内存空间失败\n");
return NULL;
}
H->len=0;
H->pre=NULL;
H->next=NULL;
return H;
}
//创建结点
pdblist create_node(datatype data)
{
pdblist new = (pdblist)malloc(sizeof(Node));
if(new == NULL)
{
printf("申请内存空间失败\n");
return NULL;
}
new->data=data;
new->pre=NULL;
new->next=NULL;
return new;
}
//头插
int insert_head(pdblist H,datatype data)
{
if(H == NULL)
{
printf("入参为空\n");
return -1;
}
pdblist new = create_node(data);
new->next = H->next;
if(H->next!=NULL)
{
H->next->pre=new;
}
new->pre=H;
H->next=new;
H->len++;
return 0;
}
//输出
int out_dblist(pdblist H)
{
if(H == NULL)
{
printf("入参为空\n");
return -1;
}
if(H->next == NULL)
{
printf("双向链表为空\n");
return -2;
}
pdblist p=H->next;
while(p!=NULL)
{
printf("%c->",p->data);
p=p->next;
}
printf("NULL\n");
return 0;
}
//尾删并读取
int dele_tail(pdblist H)
{
if(H == NULL)
{
printf("入参为空\n");
return -1;
}
if(H->next == NULL)
{
printf("双向链表为空\n");
return -2;
}
pdblist p=H;
while(p->next!=NULL)
{
p=p->next;
}
printf("%c->",p->data);
p->pre->next=p->next;
free(p);
p=NULL;
H->len--;
return 0;
}
#ifndef __DBLIST_H__
#define __DBLIST_H__
#include <myhead.h>
typedef char datatype;
typedef struct dblist
{
union
{
datatype data; //数据域
int len;
};
//指针域
struct dblist *pre;
struct dblist *next;
}Node, *pdblist;
pdblist create_head();
pdblist create_node(datatype data);
int insert_head(pdblist H,datatype data);
int out_dblist(pdblist H);
int dele_tail(pdblist H);
#endif
#include "dblist.h"
//创建一个双向链表
//将26个英文字母通过头插的方式插入到链表中
//通过尾删的方式将数据读取并删除
int main(int argc, const char *argv[])
{
pdblist H = create_head();
for(char i=97; i<=122;i++)
{
insert_head(H,i);
}
printf("插入后\n");
out_dblist(H);
printf("尾删并读取\n");
for(char i=97; i<=122;i++)
{
dele_tail(H);
}
printf("NULL\n");
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/6aeca49f2d975bc6763fbd6e65b5f124.png)