soj 2302. Queue Implementation Using a Circular Array

来源:互联网 发布:淘宝登录界面无法打开 编辑:程序博客网 时间:2024/06/06 12:31

题意:

用循环数组模拟队列。

思路:

设置头尾指针,队列大小给定了100.

有两种表示方式:

一种,head = rear的时候队列为空。

还有一种(rear-head+1+N)%N = 0时队列为空。

我选取了第一种,第二种更传统吧。

注意:

不要用指针啦,直接变量就好了。

code:

#include <iostream>#include <cstdio>using namespace std;#define N 100template <typename T>class Queue{public:int head, rear;T a[N];Queue(){head = 0;rear = 0;}~Queue(){}Queue(const Queue &q){for (int i = 0; i < N; ++ i)a[i] = q.a[i];head = q.head;rear = q.rear;}bool empty() const{return head == rear;}int size() const{return (rear-head+N) % N;}bool push(const T &x){if (size() == N-1) return false;a[rear] = x;rear ++;if (rear == N) rear = 0;return true;}bool pop(){if (size() == 0) return false;head ++;if (head == N) head = 0;return true;}const T& front() const{return a[head];}};


原创粉丝点击