作业:创建一个双向链表,将26个英文字母通过头插的方式插入到链表中,通过尾删的方式将数据读取出来并删除
#ifndef _TEXT_H
#define _TEXT_H
#include<myhead.h>
typedef int 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 "text.h"
//创建头结点
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; //新结点的前驱指向NULLnew->next=NULL; //新结点的后继指向NULLreturn 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; //不让H中的len参与输出while(p!=NULL){printf("%c->",(char)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;}p->pre->next = p->next; //让倒数第二个结点的next指向NULL//p->pre->next = NULL;free(p);p=NULL;H->len--;return 0;
}
#include"text.h"
int main()
{//创建头结点pdblist H=create_head();//调用头插函数for(int i=65;i<=90;i++){insert_head(H,i);}out_dblist(H);//调用尾删for(int i=0;i<26;i++){dele_tail(H);}out_dblist(H);return 0;
}