您的位置:首页 > 编程语言 > Java开发

JavaShowAlgorithm-使用2个队列实现栈

2017-11-19 19:40 507 查看
队列是先进先出,而栈是先进后出;

考虑到我们取栈顶元素的便利性,我们在实现时使得栈顶等于队列头;

由于栈的pop弹出栈顶元素,而队列的pop也是弹出栈顶元素,所以我们需要特别处理的是插入操作。

由于往栈中添加元素相当于往队列头添加元素,因此我们需要在两个队列中进行元素的转移,比较简单的实现是:

1.q1和q2在任一时刻至少有一个为空,即如果有元素,所以元素只在同一个队列中。 

2.当有元素需要插入时,将插入的元素插入到空的队列中,并将另一非空队列的元素转移到该队列中,于是插入的元素添加到了队列头中。

2. 当然,可以换一种思路,把队列尾与栈顶对应起来,这样子需要特别处理的是pop操作以及top操作,相比起来,本文的做法更加简便,因为只需要对插入操作特别处理)

第二种方法具体实现如下:

public class Queue2Stack {

private ArrayQueue queue1;
private ArrayQueue queue2;
private int maxLength;

public Queue2Stack(int capacity) {
maxLength = capacity;
queue1 = new ArrayQueue(capacity);
queue2 = new ArrayQueue(capacity);
}

/**
* 入栈
* @param item
* @return 入栈结果
*/
public boolean push(int item) {
if (size() == maxLength) {
return false;
}
if (queue2.isEmpty()) {
queue1.put(item);
} else {
queue2.put(item);
}
return true;
}

/**
* 出栈
* @return
*/
public Object pop() {
if (size() == 0) {
throw new IndexOutOfBoundsException("栈里已经空啦");
} else {
if (queue2.isEmpty()) {
while (queue1.size() > 1) {
queue2.put(queue1.poll());
}
return queue1.poll();
} else {
while (queue2.size() > 1) {
queue1.put(queue2.poll());
}
return queue2.poll();
}
}
}

public int size() {
return queue1.size() + queue2.size();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: