7.10作业

linkqueue.h

#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__

#include <stdio.h>
#include <stdlib.h>

typedef int datatype;

typedef struct node
{
	union 
	{
		int len;
		datatype data;
	};
	struct node *next;
}node;

typedef struct queue
{
	node *head;
	node *tail;
}linkqueue,*linkqueueptr;

//创建链式队列
linkqueueptr create();
//判空
int empty(linkqueueptr Q);
//入队
void push(linkqueueptr Q,datatype e);
//遍历
void show(linkqueueptr Q);
//出列
void pop(linkqueueptr Q);
//队列长度
int size(linkqueueptr Q);
//销毁
void freeQ(linkqueueptr Q);

#endif

linkqueue.c

#include "linkqueue.h"

//创建链式队列
linkqueueptr create()
{
	linkqueueptr Q=(linkqueueptr)malloc(sizeof(linkqueue));
	if(Q==NULL)
	{
		printf("创建失败\n");
		return NULL;
	}
	Q->head=(node *)malloc(sizeof(node));
	if(Q->head==NULL)
	{
		printf("申请失败\n");
		free(Q);
		return NULL;
	}
	Q->head->len=0;
	Q->head->next=NULL;
	Q->tail=Q->head;
	printf("创建成功\n");
	return Q;
}
//判空
int empty(linkqueueptr Q)
{
	if(Q==NULL)
	{
		printf("判空失败\n");
		return -1;
	}
	return Q->head==Q->tail;
}
//入队
void push(linkqueueptr Q,datatype e)
{
	if(Q==NULL)
	{
		printf("入队失败\n");
		return;
	}
	node *p=(node *)malloc(sizeof(node));
	if(p==NULL)
	{
		printf("申请失败\n");
		return;
	}
	p->data=e;
	p->next=NULL;
	Q->tail->next=p;
	Q->tail=p;
	Q->head->len++;
}
//遍历
void show(linkqueueptr Q)
{
	if(Q==NULL||empty(Q))
	{
		printf("遍历失败\n");
		return;
	}
	node *q=Q->head;
	while(q->next!=NULL)
	{
		q=q->next;
		printf("%d ",q->data);
	}
	printf("\n");
}
//出列
void pop(linkqueueptr Q)
{
	if(Q==NULL||empty(Q))
	{
		printf("出列失败\n");
		return;
	}
	printf("%d出列\n",Q->head->next->data);
	node *q=Q->head->next;
	Q->head->next=q->next;
	free(q);
	q=NULL;
	Q->head->len--;
}
//队列长度
int size(linkqueueptr Q)
{
	if(Q==NULL)
	{
		printf("计算失败\n");
		return -1;
	}
	return Q->head->len;
}
//销毁
void freeQ(linkqueueptr Q)
{
	if(Q==NULL)
	{
		printf("销毁失败\n");
		return;
	}
	while(Q->head->next!=NULL)
		pop(Q);
	free(Q->head);
	Q->head=NULL;
	free(Q);
	Q=NULL;
	printf("销毁成功\n");
}

main.c

#include "linkqueue.h"

int main()
{
	linkqueueptr Q=create();
	push(Q,1);
	push(Q,2);
	push(Q,3);
	show(Q);
	pop(Q);
	show(Q);
	int d=size(Q);
	printf("size=%d\n",d);
	freeQ(Q);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值