顺序队
队列可以看成是两边开口的栈,它遵守先进先出原则。
在使用顺序队时,相当于使用数组,需要提前声明一段空间。
使用两个变量分别指向队头和队尾。
#include <iostream> #include <vector> using namespace std; int enQueue(vector<int> &vec, int rear, int elem) { vec[rear] = elem; ++rear; return rear; } void deQueue(vector<int> &vec, int front, int rear) { while (front != rear) { cout << vec[front] << "出列!" << endl; ++front; } } int main() { vector<int> vec(10, 0); int front = 0, rear = 0; rear = enQueue(vec, rear, 5); rear = enQueue(vec, rear, 10); rear = enQueue(vec, rear, 8); rear = enQueue(vec, rear, 1); rear = enQueue(vec, rear, 6); rear = enQueue(vec, rear, 9); deQueue(vec, front, rear); system("PAUSE"); return 0; }
因为顺序队需要指定大小,所以创建的队列大小也是有效且一次性的,这时候就可以使用循环队列,对首尾进行连接,可以对指定大小空间进行重复利用。
#include <iostream> #include <vector> #define MAX 3 using namespace std; int Enqueue(vector<int> &vec, int rear, int elem) { if (rear < MAX) { vec.push_back(elem); ++rear; } else { vec[rear % MAX] = elem; ++rear; } return rear; } void Dequeue(vector<int> &vec, int front, int rear) { if (front == rear) { cout << "队列为空!" << endl; return; } while (front != (rear > MAX ? ((rear - 1) % MAX + 1 ): rear)) {//(rear - 1) % MAX求该位置的元素位置,+1为判断条件 cout << vec[front] << "出列" << endl; ++front; } } int main() { vector<int> vec; int front, rear; front = rear = 0; rear = Enqueue(vec, rear, 1);//入列 rear = Enqueue(vec, rear, 2); rear = Enqueue(vec, rear, 3); Dequeue(vec, front, rear);//出列 rear = Enqueue(vec, rear, 4); rear = Enqueue(vec, rear, 5); rear = Enqueue(vec, rear, 6); Dequeue(vec, front, rear); rear = Enqueue(vec, rear, 7); rear = Enqueue(vec, rear, 8); Dequeue(vec, front, rear); system("PAUSE"); return 0; }
- 当队列为空时,队列的头指针等于队列的尾指针;
- 当数组满员时,队列的头指针等于队列的尾指针;