方法1:用一个对列实现栈,其实复杂在入队,其他都是直接调用系统方法,入队,如果入队之后,队长度为1,不进行操作,否则,就把刚入队的元素调整到栈顶(队首)其实就是把其余元素在入队,这样构成的对列,始终和栈的结构是一样的
class MyStack {
LinkedList<Integer> l1=new LinkedList();
/** Initialize your data structure here. */
public MyStack() {
l1=new LinkedList();
}
/** Push element x onto stack. */
public void push(int x) {
l1.add(x);
if(l1.size()==0){
return;
}
int length=l1.size()-1;
while(length>0){
l1.add(l1.poll());
length--;
}
}
public int pop() {
return l1.poll();
}
/** Get the top element. */
public int top() {
return l1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return l1.size()==0;
}
}
方法2:用一个临时对列help,这个重点是出队,每次出队,都要把对列的n-1个元素放到help对列,然后输出最后一个元素,然后交换help和对列的引用,保证每次取元素都是在非help对列,保证代码的可用性。
class MyStack {
Queue<Integer> qu;
Queue<Integer> help;
/** Initialize your data structure here. */
public MyStack() {
qu=new LinkedList<Integer>();
help=new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
qu.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while(qu.size()>1){
help.add(qu.poll());
}
int temp=qu.poll();
swap();
return temp;
}
/** Get the top element. */
public int top() {
if(qu.size()==1){
return qu.peek();
}
while(qu.size()>1){
help.add(qu.poll());
}
int temp=qu.poll();
help.add(temp);
swap();
return temp;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return qu.size()==0;
}
public void swap(){
Queue<Integer> temp=qu;
qu=help;
help=temp;
}
}
这里又爆了一个奇葩的错,就是swap参数,如果我传help和qu就会报空指针,这不是引用吗??,为什么就报错呢??/