所以我试图用一个队列实现一个堆栈,它看起来可以工作,但我不确定它是否有问题,因为我在网上看到的大多数解决方案都使用两个队列。任何人都可以告诉我,如果我的执行有问题吗?Java:用一个队列实现堆栈,有什么问题?
public class MyStack<T> {
/**
* @param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
输出:
空
如果你想代码审查这不是网站,你有一个意想不到的行为? – nachokk
没有意外的行为。我只是想知道为什么大多数在线解决方案使用两个队列时,似乎工作得很好。 – user2017502
从来没有见过用2个队列实现的堆栈,你见过的解决方案是什么?此外,为什么'Queue'因为是FIFO而Stack是LIFO。 – zapl