好久没写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());
}
}
}