【算法导论】用两个堆实现栈

好久没写java了,用java实现一个吧;

用两个堆实现栈:

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

interface Stacked<E> {
	void push(E newElement);
	E pop();
}

class OutofRangeException extends RuntimeException {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public OutofRangeException(String message) {
        super(message);
    }
}

// 用队列实现栈
public class Stack<E> implements Stacked<E> {
	protected static final int QUEUE_SIZE = 100;
	protected static final int TOTAL_SIZE = 2 * QUEUE_SIZE;
	
	public static final int STACK_SIZE = QUEUE_SIZE;
	
	protected Queue<E> queue = new ArrayBlockingQueue<E>(QUEUE_SIZE);
	protected Queue<E> backupQueue = new ArrayBlockingQueue<E>(QUEUE_SIZE);
	
	public Stack() { }
	
	@Override
	public void push(E newElement) {
		if (this.queue.size() >= QUEUE_SIZE) 
			throw new OutofRangeException("Out of Range");
		this.queue.add(newElement);
	}

	@Override
	public E pop() {
		E result = popQueueToBackupQueue();;
		popBackupQueueToQueue();
		return result;
	}
	
	// 以倒序复制到backupQueue中
	protected E popQueueToBackupQueue() {
		while (queue.size() != 1) {
			backupQueue.add(queue.remove());
		}
		return queue.remove();
	}
	
	// 以倒序复制到queue中
	protected void popBackupQueueToQueue() {
		while (!backupQueue.isEmpty()) {
			queue.add(backupQueue.remove());
		}
	}
	
}


用两个栈实现堆的做法类似上面;



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值