队列基础知识总结
队列定义
特点:FIFO(先入先出)
操作:入队(push)、出队(pop)、判空(empty)、判满(full)、清空(clear)
顺序队列
顺序队列就是按照FIFO的特性,每次pop、push元素的时候,head、tail指针就会向后面移动一步,但是经过多次入队和出队操作的时候,会造成前面被出队元素原本的存储空间浪费。
循环队列
为了解决顺序队列的浪费大量使用过的空间问题(内存泄漏),循环队列就是在每次pop、push操作的时候需要判断head、tail所在位置是不是顺序存储空间的最后一个元素位置,同时判断cnt是否大于等于存储空间size的大小。当cnt小于size时候,判断head、tail是否处于空间最后的位置queue[size],如果处于,就将tail和head置为0(顺序存储空间的首位置);
队列实现【C++】
//顺序队列
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class queue {
public :
queue(int n) : size(n), arr(n), head(0), tail(0) {};
void push(int val) {
if (is_full()) {
cout << "queue is full" << endl;
return ;
}
arr[tail++] = val;
return ;
}
void pop() {
if (is_empty()) {
cout << "queue is empty" << endl;
return ;
}
head++;
return ;
}
bool is_full() {
return tail == size;
}
bool is_empty() {
return tail == 0;
}
void output() {
for (int i = head; i < tail; i++) {
if (i != head) cout << " ";
cout << arr[i];
}
cout << endl;
}
void clear() {
head = tail = 0;
return ;
}
~queue() {};
private :
int size;
int head;
int tail;
vector<int> arr;
};
int main() {
queue que(5);
string opt;
int val;
while (cin >> opt) {
if (opt == "push") {
cin >> val;
que.push(val);
} else if (opt == "pop") {
que.pop();
} else if (opt == "clear") {
que.clear();
} else {
cout << "Usage : input \"push | pop | clear\" to use !" << endl;
}
que.output();
}
return 0;
}
//循环队列
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class queue {
public :
queue(int n) : size(n), arr(n), head(0), tail(0), cnt(0) {};
void push(int val) {
if (is_full()) {
cout << "queue is full" << endl;
return ;
}
arr[tail] = val;
cnt++;
if (++tail == size) tail = 0;
return ;
}
void pop() {
if (is_empty()) {
cout << "queue is empty" << endl;
return ;
}
if (++head == size) head = 0;
cnt--;
return ;
}
bool is_full() {
return cnt == size;
}
bool is_empty() {
return cnt == 0;
}
void output() {
for (int i = 0, j = head; i < cnt; i++) {
if (i != 0) cout << " ";
cout << arr[j];
if (++j == size) j = 0;
}
cout << endl;
}
void clear() {
head = tail = 0;
cnt = 0;
return ;
}
~queue() {};
private :
int size;
int cnt;
int head;
int tail;
vector<int> arr;
};
int main() {
queue que(5);
string opt;
int val;
while (cin >> opt) {
if (opt == "push") {
cin >> val;
que.push(val);
} else if (opt == "pop") {
que.pop();
} else if (opt == "clear") {
que.clear();
} else {
cout << "Usage : input \"push | pop | clear\" to use !" << endl;
}
que.output();
}
return 0;
}