国庆作业2

#include 
#include 

typedef int datatype;
typedef struct dblist
{
    union
    {
        datatype data;  //数据域
        int len;    
    };
	//指针域
    struct dblist *pre;   //前驱
    struct dblist *next;  //后继
}Node,*pdblist;

//创建头结点
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;   //新结点的前驱指向NULL
	new->next=NULL;  //新结点的后继指向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 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;   //让倒数第二个结点的next指向NULL
	free(p);
	p=NULL;
	H->len--;
	return 0;
}
int main()
{
	pdblist H = create_head();
	char i = 0;
	for(i = 'a'; i <= 'z'; i++){
		insert_head(H, i);
	}
	for(i = 'a'; i <= 'z'; i++){
		dele_tail(H);
	}
	putchar(10);
	H = NULL;

	return 0;
}

你可能感兴趣的:(c语言,数据结构,算法)