【发布时间】:2016-03-10 16:16:23
【问题描述】:
我最近来到队列数据结构。为了练习和学习新的东西,我决定在没有 STL 库的情况下实现它。问题是,我很难真正分辨典型数组和队列之间的区别。
我定义了简单的类
class Queue{
public:
Queue();
Queue(int);
void enqueue(int);
int dequeue();
int first_out() ;
int last_out() ;
bool isEmpty();
bool isFull();
private:
int current;
int maxi;
int *arr;
int frontt;
int rear;
};
它的构造函数
Queue::Queue(int maxo){
this -> current = 0;
this -> maxi = maxo;
this -> arr = new int[maxi];
this -> frontt = 0;
this -> rear = 0;
}
enqueue 方法,当尝试访问大于最大索引的索引时,重新分配内部数组。
void Queue::enqueue(int a){
if( this -> rear == this -> maxi){
int *temp;
int tmp = maxi;
while( this -> rear >= this -> maxi){
this -> maxi *= 2;
}
temp = new int[maxi];
for( int i = 0; i < tmp ; i++){
temp[i]=arr[i];
}
rear = maxi;
delete[] arr;
arr = temp;
}
this -> arr[rear++] = a;
}
增加前索引的出队。
int Queue::dequeue(){
return arr[frontt++];
}
int Queue::first_out(){
return arr[frontt];
}
int Queue::last_out(){
return arr[rear-1];
}
bool Queue::isEmpty(){
if( this -> frontt == this -> rear){
cout << "Queue is empty" << endl;
return 1;
}
return 0;
}
bool Queue::isFull(){
if( this -> frontt == (this -> rear+1) % this -> maxi){
return 1;
}
return 0;
}
测试它的主要功能
Queue tst(5);
cout << "Write numbers" << endl;
int n;
while( cin >> n){
tst.enqueue(n);
}
tst.dequeue();
cout << "The firt out element is " << tst.first_out() << endl;
cout << "The last out element is " << tst.last_out() << endl;
return 0;
我的问题很简单。这是如何实现队列?我可以将其理解为队列只是值的生成器/迭代器吗?那为什么要使用队列而不是数组呢?还有循环队列的意义何在?
感谢您的回答。
【问题讨论】:
-
为什么不看看 c++ 标准库的实现并与你的比较一下?