常量时间的队列操作(min/max)

要想实现带有min,max常量时间操作的队列,不能直接通过增加额外的空间来实现,但是可以通过使用带有min,max常量时间操作的两个栈来实现!

栈1用于接受加入队列的数据,push操作时总是会把数据压入栈1,pop时总是弹出栈2,如果栈2为空是就将栈1的数据依次弹出压入栈2!这样便使用两个栈实现了一个队列,由于栈有常量时间的min,max操作,队列也拥有了常量时间的min,max操作。

#include <iostream>
#include <stack>
using namespace std;

template<typename type>
class xstack
{
public:
	void push(const type v) {
		if (stk.empty()) {
			min_stk.push(v);
			max_stk.push(v);
		} else {
			if (v <= min_stk.top())
				min_stk.push(v);
			if (v >= max_stk.top())
				max_stk.push(v);
		}
		stk.push(v);
	}

	void pop() {
		type v = stk.top();
		if (v == min_stk.top())
			min_stk.pop();
		if (v == max_stk.top())
			max_stk.pop();
		stk.pop();
	}

	type top() {
		return stk.top();
	}

	size_t size() {
		return stk.size();
	}

	bool empty() {
		return stk.empty();
	}

	type min() {
		return min_stk.top();
	}

	type max() {
		return max_stk.top();
	}

private:
	stack<type> stk;
	stack<type> min_stk;
	stack<type> max_stk;
};

template<typename type>
class xqueue
{
public:
	void push(const type v) {
		stk1.push(v);
	}

	void pop() {
		type v = front();
		stk2.pop();
	}

	type front() {
		if (stk2.empty()) {
			while (!stk1.empty()) {
				stk2.push(stk1.top());
				stk1.pop();
			}
		}
		return stk2.top();
	}

	size_t size() {
		return stk1.size() + stk2.size();
	}

	bool empty() {
		return stk1.empty() && stk2.empty();
	}

	type min() {
		if (stk1.empty() && !stk2.empty())
			return stk2.min();
		if (!stk1.empty() && stk2.empty())
			return stk1.min();
		return std::min(stk1.min(), stk2.min());
	}

	type max() {
		if (stk1.empty() && !stk2.empty())
			return stk2.max();
		if (!stk1.empty() && stk2.empty())
			return stk1.max();
		return std::max(stk1.max(), stk2.max());
	}

private:
	xstack<type> stk1;
	xstack<type> stk2;
};

int main()
{
	xqueue<int> x;
	x.push(9);
	x.push(5);
	x.push(8);
	cout << x.min() << " " << x.max()<< endl;
	x.push(6);
	x.push(1);
	cout << x.min() << " " << x.max()<< endl;
	x.push(4);
	x.push(3);
	x.push(2);
	cout << x.min() << " " << x.max()<< endl;
	x.push(7);
	x.push(0);
	x.pop();
	x.pop();
	cout << x.min() << " " << x.max()<< endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值