所以我尝试实现一个只有一个队列的堆栈,它似乎可以工作,但我不确定它是否有问题,因为我在网上看到的大多数解决方案都使用两个队列。谁能告诉我我的实现是否存在问题?
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();
}
}
输出:
4
3
2
1
空
最佳答案
您的解决方案效率低下,因为每次从堆栈中弹出内容时都必须循环遍历整个堆栈。 (实际上,在删除末尾的元素之前,您必须遍历整个链表。) 编辑:Java 的链表无论如何都是双向链接的,所以这是完全没有意义的。
关于Java:用一个队列实现堆栈,有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18047647/