基本原则:
先进先出,后进后出。 FIFO
普通队列
#include <iostream>
#include <cassert>
using namespace std;
class Queue {
private:
int *data;
int head, tail, length;
public:
Queue(int length_input) {
data = new int[length_input];
length = length_input;
head = 0;
tail = -1;
}
队列的构成:保存数据的数组 data【】
** 队列长度,也就是数组长度加一,length**
** 记录队首元素位置的head(index)**
** 记录队尾元素位置的tail(index)**
~Queue() {
delete[] data;
}
---
##入队
void push(int element) {
if (tail + 1 < length) {
tail++;
data[tail] = element;
}
}
>**思路:直接将tail++,然后将入队的值赋予data[tail]**
---
** **
void output() {
for (int i = head; i <= tail; i++) {
cout << data[i] << " ";
}
cout << endl;
}
** **
int front(){
assert(head<=tail);
return data[head];
}
##出队
** **
void pop(){
assert(head<=tail);
head++;
}
**思路:直接将记录队首元素的head++;**
** **
};
int main() {
Queue queue(100);
for (int i = 1; i <= 10; i++) {
queue.push(i);
}
queue.output();
cout<< queue.front()<<endl;
queue.pop();
queue.output();
return 0;
}
------------------------------------------------------------------------------------------------
##循环队列
include <iostream>
include <cassert>
using namespace std;
class Queue {
private:
int *data;
int head, tail, length, count;
public:
Queue(int length_input) {
data = new int[length_input];
length = length_input;
head = 0;
tail = -1;
count = 0;
}
**队列的构成:保存数据的数组 data【】**
** 队列长度,也就是数组长度加一,length**
** 记录队首元素位置的head(index)**
** 记录队尾元素位置的tail(index)**
** 记录队列元素数量的count**
** **
~Queue() {
delete[] data;
}
bool push(int element) {
if (count < length) {
tail = (tail + 1) % length;
data[tail] = element;
count++;
return true;
} else {
return false;
}
}
void output() {
for (int i = head; i != tail + 1; i = (i + 1) % length) {
cout << data[i] << " ";
}
cout << endl;
}
int front() {
assert(count>0);
return data[head];
}
void pop() {
assert(count>0);
head=(head+1)%length;
count--;
}
};
int main() {
Queue queue(100);
for (int i = 1; i <= 10; i++) {
queue.push(i);
}
queue.output();
cout << queue.front() << endl;
queue.pop();
queue.output();
return 0;
}
网友评论