链表实现队列and实现循环队列

//链表实现队列
#include <stdio.h>
#include<stdlib.h>
typedef int elemType;
typedef struct LinkNode {
	elemType data;
	LinkNode* next;
}LinkNode;
typedef struct {
	LinkNode* front;
	LinkNode* tail;
}LinkQueue;  //先进先出
bool initQueue(LinkQueue &Q) {

	Q.front = Q.tail = (LinkNode*)malloc(sizeof(LinkNode));  //让头结点和尾节点指向同一块空间
	Q.front->next = NULL;

	return true;
}
bool inQueue(LinkQueue& Q, int num) {
	LinkNode* pnew = (LinkNode*)malloc(sizeof(LinkNode));
	pnew->data = num;
	pnew->next = NULL;

	Q.tail->next = pnew; //第一次插入时,这里Q.front->next也指向了第一个节点
	Q.tail = pnew;//让尾指针一直指向最后一个元素


	return true;
}
bool outQueue(LinkQueue& Q) {
	if (Q.front == Q.tail) return false;
	LinkNode* p;
	p = Q.front->next;//头结点没有值,头结点的下一个值
	Q.front->next = p->next;

	//如果删除的是最后一个节点,我们要将队列置空
	if (Q.tail == p)
	{
		Q.front = Q.tail;
	}
	free(p);


	return true;
}
int main() {
	//队列从队尾入队,从队头出队

	LinkQueue queue;
	
	initQueue(queue); //初始化队列
	//使用尾插法 插入
	inQueue(queue,1);
	inQueue(queue,2);
	inQueue(queue,3);
	//使用头部删除法出队列
	outQueue(queue);
	outQueue(queue);
	outQueue(queue);


	return 0;
}
//实现循环队列
#include <stdio.h>
#include<stdlib.h>
#define MaxSize 5
typedef int elemType;
typedef struct {
	elemType data[MaxSize]; // 循环链表最多可存MaxSize-1个元素
	elemType front, tail;
}SqQueue;

bool initQueue(SqQueue& Q) {
	Q.front = Q.tail = 0;
	return true;
}
bool isEmpty(SqQueue Q) {
	if (Q.front==Q.tail)
	{
		printf("队列为空\n");
		return true;
	}
	return false;
}
bool InQueue(SqQueue& Q, elemType num) {
	//判断队列是否已满
	if ((Q.tail+1)%MaxSize==Q.front)
	{
		printf("插入失败,队列已满\n");
		return false;
	}
	Q.data[Q.tail] = num;
	Q.tail=(Q.tail+1)%MaxSize;
	return true;
}
bool OutQueue(SqQueue& Q) {
	//判断队列是否为空
	if (isEmpty(Q))
	{
		printf("队列为空,出队失败\n");
		return false;
	}
	printf("%d出队列\n", Q.data[Q.front]);
	Q.front = (Q.front + 1) % MaxSize;
	return true;

}
int main() {
	SqQueue queue;
	initQueue(queue);//初始化循环队列
	isEmpty(queue);//判断队列是否为空
//尾插法 进队列
	InQueue(queue, 1);
	InQueue(queue, 2);
	InQueue(queue, 3);
//头部删除法 出队列
	OutQueue(queue);
	OutQueue(queue);
	OutQueue(queue);
	OutQueue(queue);

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值