队列是指具有一定操作约束的线性表
数据只能在一端进行插入,在另外一端执行删除
先进先出 先来先服务
环状队列如何判断队列何时为空 何时为满?
如果 队尾+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;
}