带Max函数的队列

编程之美上的一个题目。

感觉上面用数组的方法不是很好理解。于是自己写了一下。也是用了两个栈来维护一个队列。同时又多出两个栈,分别维护之前两个栈里面的最大值。然后求Max函数的时候,值需要返回后两个栈的的最大值即可。

看代码:

package a;

import java.util.Stack;

public class Test1 {

	public static void main(String s[]) {
		//5 6 3 7 2 1
		QueueM q = new QueueM();
		q.enqueue(5);
		int m = q.max();
		q.enqueue(6);
		m = q.max();
		q.enqueue(3);
		int d = q.dequeue();
		q.enqueue(7);
		m = q.max();
		q.enqueue(2);
		m = q.max();
		q.enqueue(1);
		d = q.dequeue();
		m = q.max();
		d = q.dequeue();
		m = q.max();
		d = q.dequeue();
		m = q.max();
	}

}

class QueueM {

	static final int INF = 111111111;
	Stack<Integer> stack1 = new Stack<Integer>();
	Stack<Integer> stack1_m = new Stack<Integer>();
	Stack<Integer> stack2 = new Stack<Integer>();
	Stack<Integer> stack2_m = new Stack<Integer>();

	public void enqueue(int obj) {
		stack1.push(obj);
		if (stack1_m.size() == 0) {
			stack1_m.push(obj);
		} else {
			int d = stack1_m.peek();
			if (d < obj) {
				stack1_m.push(obj);
			} else {
				stack1_m.push(d);
			}
		}
	}

	public int dequeue() {
		if (stack2.isEmpty()) {
			int n = stack1.size();
			for (int i = 0; i < n; i++) {
				int d = stack1.pop();
				stack1_m.pop();
				stack2.push(d);
				if (stack2_m.size() == 0) {
					stack2_m.push(d);
				} else {
					if (d > stack2_m.peek()) {
						stack2_m.push(d);
					} else {
						stack2_m.push(stack2_m.peek());
					}
				}
			}
		}
		if (stack2.isEmpty()) {
			return INF * -1;
		} else {
			int d = stack2.pop();
			stack2_m.pop();// 相应位置的最大值也出栈
			return d;
		}
	}

	public int max() {
		if (stack1_m.size() == 0 && stack2_m.size() == 0) {
			return -1 * INF;
		}
		if (stack1_m.size() == 0 && stack2_m.size() != 0) {
			return stack2_m.peek();
		}
		if (stack1_m.size() != 0 && stack2_m.size() == 0) {
			return stack1_m.peek();
		}
		return stack1_m.peek() > stack2_m.peek() ? stack1_m.peek() : stack2_m
				.peek();
	}
}

代码中的max()函数就是返回了两个栈里的 最大值。这样,就很好理解了。比直接用数组好理解的多。

题目中我用563721这几个数字来模拟操作。思路与何海涛的书中求栈的最大值的思路类似。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值