数据结构-循环队列(非链表实现和链表实现)

非链表实现

#include<iostream>
#define MaxSize 50
using namespace std;
typedef int ElemType;

typedef struct Queue{
	ElemType data[MaxSize];
	int front;
	int rear;
}Queue; 
void InitQueue(Queue &Q){
	Q.front = 0;
	Q.rear = 0;
}
bool isEmpty(Queue Q){
	if(Q.front==Q.rear)
		return true;
	return false;
}
//顺序队列存在假溢出现象,使用循环队列
//循环队列空出一个存储单元,来区别队满和队空的区别 
bool push(Queue &Q,ElemType e){
	if((Q.rear+1)%MaxSize==Q.front)		//队列满 
		return false;
	Q.data[Q.rear] = e;
	Q.rear = (Q.rear+1)%MaxSize; 
}
bool pop(Queue &Q,ElemType &e){
	if(Q.front==Q.rear)		//判断队空 
		return false;
	e = Q.data[Q.front];
	Q.front = (Q.front+1)%MaxSize;
}
int main()
{
	Queue Q;
	ElemType e;
	InitQueue(Q);
	push(Q,5);
	push(Q,55);
	push(Q,79);
	push(Q,6);
	push(Q,24);
	while(!isEmpty(Q)){
		pop(Q,e);
		cout<<"出队元素:"<<e<<endl;
	}
	return 0;
}

链表实现

#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef int ElemType;
typedef struct Node{
	ElemType data;
	struct Node* next;
}*LinkNode;
typedef struct Queue{
	LinkNode front;
	LinkNode rear;
}Queue;
void InitQueue(Queue &Q){
	Q.front=Q.rear=(LinkNode)malloc(sizeof(Node));//带头结点更方便哦 
	Q.front->next = NULL;
}
bool isEmpty(Queue Q){
	if(Q.front==Q.rear)
		return true;
	return false;
}
bool push(Queue &Q,ElemType e){
	
	LinkNode s = (LinkNode)malloc(sizeof(Node));
	s->data = e;
	s->next=NULL;	//这是队尾所以下一个一定要指向NULL
	Q.rear->next = s;
	Q.rear = s; 
	return true;
}
bool pop(Queue &Q,ElemType &e){
	if(isEmpty(Q))	return false;
	LinkNode p = Q.front -> next;
	e = p->data;
	Q.front->next = p->next;
	if(Q.rear==p)
		Q.rear = Q.front;
	free(p);
	return true;
}
int main()
{
	Queue Q;
	ElemType e;
	InitQueue(Q);
	push(Q,5);
	push(Q,3);
	push(Q,6);
	push(Q,8);
	push(Q,99);
	while(!isEmpty(Q)){
		pop(Q,e);
		cout<<"出队元素:"<<e<<endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值