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

推荐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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值