假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点(注意不设头指针),试编写相应的置空队列、判断队列是否为空、入队和出队等算法。

typedef int Datatype;
typedef struct queue
{
	Datatype data;
	struct queue* next;
}queue;
//队列
typedef struct
{
	queue* rear;
}LinkQueue;
//初始化
void queueinit(LinkQueue* ps)
{
	ps->rear = (queue*)malloc(sizeof(queue));
	if (ps->rear == NULL)
	{
		perror("error");
		exit(1);
	}
	ps->rear->next = ps->rear;//初始化循环链表
}
//判空
int Empty(LinkQueue* ps)
{
	return ps->rear == ps->rear->next;//头尾相等,为空
}
//入队
int push(LinkQueue* ps, int e)
{
	queue* newnode = (queue*)malloc(sizeof(queue));
	if (newnode == NULL)
	{
		perror("error:");
		exit(1);
	}
	newnode->data = e;
	newnode->next = ps->rear->next;//新节点指向原队首
	ps->rear->next = newnode;
	if (ps->rear == ps->rear->next)
	{
		ps->rear = newnode;
	}
}
int pop(LinkQueue* ps)
{
	if ((Empty(&ps)))
	{
		printf("栈为空,无输出内容\n");
		return -1;
	}
	//出队是头出,
	queue* temp = ps->rear->next;//临时节点指向队首
	int ret = temp->data;
	ps->rear->next = temp->next;//尾节点直接指向原队首的下一个节点
	if (ps->rear->next == ps->rear)
	{
		ps->rear->next = ps->rear;
	}
	free(temp);
	return ret;
}

int main()
{
	LinkQueue ps;
	queueinit(&ps);
	push(&ps, 1);
	push(&ps, 2);
	printf("出队情况\n");
	printf("%d\n", pop(&ps));
	printf("%d\n", pop(&ps));
	int ret = Empty(&ps);
	if (ret == 1)
	{
		printf("队列元素已全出队\n");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值