您的位置:首页 > 编程语言

编程之美3.7——队列中取最大值操作问题

2013-08-22 16:40 369 查看
推荐http://blog.csdn.net/linyunzju/article/details/7765324
http://www.cnblogs.com/kurtwang/archive/2010/09/22/1833132.html
问题:

假设有这样一个拥有3个操作的队列:

1. EnQueue(v): 将v加入队列中

2. DeQueue(): 使队列中的队首元素删除并返回此元素

3. MaxElement: 返回队列中的最大元素

设计一种数据结构和算法,让MaxElement操作的时间复杂度尽可能地低。

#include <iostream>
using namespace std;
class Stack{
private:
int stackItem[20];
int stackTop;
int nextmaxitem[20];
int maxindex;
public:
Stack(){
stackTop=-1;
maxindex=-1;
}
void push(int x){
stackTop++;
if(stackTop>=20){
cout<<"full"<<endl;
return;
}
stackItem[stackTop]=x;
if(x>max()){
nextmaxitem[stackTop] = maxindex;
maxindex = stackTop;
}else{
nextmaxitem[stackTop]=-1;
}
}
int pop(){
if(stackTop<0){
cout<<"empty"<<endl;
return -1000;
}
int ret = stackItem[stackTop];
if(ret==stackItem[maxindex]){
maxindex = nextmaxitem[stackTop];
}
stackTop--;
return ret;
}
int max(){
if(maxindex>=0)
return stackItem[maxindex];
else
return -10000;
}
bool empty(){
if(stackTop<0)
return true;
return false;
}
};
class Queue{
private:
Stack stacka;
Stack stackb;
public:
int maxvalue(int x,int y){
return x>y?x:y;
}
int max(){
return maxvalue(stacka.max(),stackb.max());
}
void enque(int x){
stackb.push(x);
}
int deque(){
if(stacka.empty()){
while(!stackb.empty()){
stacka.push(stackb.pop());
}
}
return stacka.pop();
}
};
int main(){
/*Stack s;
s.push(1);
s.push(21);
s.push(3);
cout<<"max is:"<<s.max()<<endl;
cout<<"pop is:"<<s.pop()<<endl;
cout<<"max is:"<<s.max()<<endl;
cout<<"pop is:"<<s.pop()<<endl;
cout<<"max is:"<<s.max()<<endl;
cout<<"pop is:"<<s.pop()<<endl;
cout<<"max is:"<<s.max()<<endl;
*/
Queue que;
que.enque(1);
que.enque(2);
que.enque(13);
que.deque();
que.enque(4);
que.enque(5);
cout<<que.max()<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程之美