版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cjh_android/article/details/84304393
题目
-
使用堆栈实现队列的以下操作:
- push(x) - 将元素x推送到队列的后面。
- pop() - 从队列前面删除元素。
- peek() - 获取前面的元素。
- empty() - 返回队列是否为空。
-
要求:
- 必须仅使用堆栈的标准操作 - 这意味着只能从顶部添加元素、查看/弹出;队列大小,判空空操作是有效的。
- 由于语言不同,可能不支持原生堆栈。 您可以使用列表或双端队列(双端队列)来模拟堆栈,只要您只使用堆栈的标准操作即可。
- 您可以假设所有操作都是有效的(例如,不会在空队列上调用pop或Peek操作)。
分析
对于java而言,也就是使用 Stack 来实现 Queue…
后记:事实上这条题目比我预估的要难一点,用三个 stack 我能解决,用两个 stack ,参考了别的代码,做了点优化…这比用 queue 实现 stack 要难。
思路
在使用两个 stack 的做法中,其中一个stack是用来记录需要pop的元素
代码
package algorithm016;
import java.util.Stack;
public class Algorithm016 {
public static void main(String[] args) {
IQueue<Integer> queue = new StackQueue<Integer>();
System.out.println(queue.pop());
System.out.println(queue.peek());
queue.push(4);
System.out.println(queue.peek());
System.out.println(queue.pop());
queue.push(1);
queue.push(0);
System.out.println(queue.pop());
System.out.println(queue.peek());
queue.push(12);
queue.push(2);
queue.push(9);
queue.push(5);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}
interface IQueue<E>{
E push(E item);
E pop();
E peek();
boolean empty();
}
class StackQueue<E> implements IQueue<E> {
Stack<E> stackTemp = new Stack<E>();
Stack<E> stack = new Stack<E>();
@Override
public E push(E item) {
if(item != null)
stackTemp.push(item);
return item;
}
@Override
public E pop() {
if(stack.empty() && stackTemp.empty())
return null;
if(stack.empty() && !stackTemp.empty())
peek();
return stack.pop();
}
@Override
public E peek() {
if(stack.empty())
while(stackTemp.size() != 0) {
stack.push(stackTemp.pop());
}
if(stack.empty() && stackTemp.empty())
return null;
return stack.peek();
}
@Override
public boolean empty() {
return stack.empty() && stackTemp.empty();
}
}