提示:定義一個數組,用兩個指針表示隊列的首尾位置,編寫兩個函數代表出隊入隊操作。當隊列長度超過數組長度時,提示隊列超長,當隊列空時,提示隊列為空。主程序實現對隊列的調用,
#include <iostream>
using namespace std;
#define ARRSIZE 5
class Queue
{
private:
int * arr;
int * start;
int * end;
int length;
public:
Queue()
{
arr = new int[ARRSIZE];
start = end = arr;
length = 0;
}
void enqueue(int x)
{
if (length == ARRSIZE)
{
cout << "full" << endl;
throw "error";
}
else
{
*start = x;
*start--;
length++;
if (start < arr) start = &arr[ARRSIZE - 1];
}
}
int dequeue()
{
if (!length)
{
cout << "empty" << endl;
throw "error";
}
else
{
int result = *end;
*end--;
length--;
if (end < arr) end = &arr[ARRSIZE - 1];
return result;
}
}
};
int main(int argc, _TCHAR* argv[])
{
Queue q = Queue();
q.enqueue(1);
cout << q.dequeue() << endl;
q.enqueue(2);
q.enqueue(3);
cout << q.dequeue() << endl;
cout << q.dequeue() << endl;
q.enqueue(4);
q.enqueue(5);
q.enqueue(6);
cout << q.dequeue() << endl;
cout << q.dequeue() << endl;
q.enqueue(7);
cout << q.dequeue() << endl;
cout << q.dequeue() << endl;
q.enqueue(8);
cout << q.dequeue() << endl;
return 0;
}