数据结构 队列的实现

队列是指具有一定操作约束的线性表

数据只能在一端进行插入,在另外一端执行删除

先进先出 先来先服务


环状队列如何判断队列何时为空 何时为满?

如果 队尾+1%MAXSIZE = 队头 则队列为满

如果 队头 == 队尾 则队列为空


队列的数组实现:

#include<iostream>
#include<stdlib.h>
#define MAXSIZE 6
using namespace std;
typedef int ElementType;

//循环队列实现
struct QUEUE
{
	int data[MAXSIZE];
	int head = 0;    //头指针
	int rear = 0;    //尾指针
};


void push(QUEUE* q, ElementType element) {
	
	if ((q->head + 1) % MAXSIZE == q->rear) {    //通过%MAXSIZE来判断数组是空还是满
		cout << "The Queue has been full!!" << endl;
		return;
	}

	q->data[q->head] = element;            
	q->head = (q->head + 1) % MAXSIZE;

}


ElementType pop(QUEUE* q) {
	
	//判断队列是否为空?
	if (q->head == q->rear) {
		cout << "The Queue is Empty!!" << endl;
		return 0;
	}
	
	q->data[q->rear] = NULL;
	q->rear = (q->rear + 1) % MAXSIZE;
}


int main() {

	QUEUE myQueue;
	
	push(&myQueue, 10);
	push(&myQueue, 20);
	push(&myQueue, 30);
	push(&myQueue, 40);
	push(&myQueue, 50);
	
	pop(&myQueue);
	pop(&myQueue);
	pop(&myQueue);
	pop(&myQueue);
	pop(&myQueue);
	
	system("PAUSE");
	return 0;
}


队列的循环链表实现:

#include<iostream>
#include<stdlib.h>
#define MAXSIZE 6
using namespace std;
typedef int ElementType;

class NODE{
	friend class QUEUE;
private:
	ElementType data;   //数据域
	NODE* link;        //指针域
};

class QUEUE {
private:
	NODE* first;
public:
	QUEUE() {
		first = new NODE();
		first->link = first;    //头节点指向自己
	}

	void show();
	void push(ElementType data);
	ElementType pop();
};


void QUEUE::push(ElementType data){
	
	NODE* newNode = new NODE();
	newNode->data = data;
	
	newNode->link = first->link;
	first->link = newNode;
}


ElementType QUEUE::pop() {
	NODE* temp;
	NODE* Ptr;

	Ptr = first->link;
	if (Ptr == first) {
		cout << "The Queue has been full!" << endl;
		return 0;
	}

	while (Ptr->link->link != first)
		Ptr = Ptr->link;

	int tempData = Ptr->link->data;
	
	temp = Ptr->link;
	Ptr->link = first;
	delete temp;
	
	return tempData;
}

void QUEUE::show() {
	NODE* Ptr;
	Ptr = first->link;
	while (Ptr != first) {
		cout << Ptr->data << endl;
		Ptr = Ptr->link;
	}
}




int main() {


	QUEUE myQueue;
	myQueue.push(10);
	myQueue.push(20);
	myQueue.push(30);
	myQueue.push(40);

	myQueue.show();
	cout << endl << endl;

	int a = myQueue.pop();
	int b = myQueue.pop();
	int c = myQueue.pop();
	
	cout << c << endl;
	myQueue.pop();
	system("PAUSE");
	return 0;
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值