java:
在java中用linkedlist来实现队列
此题用队列来实现栈只需要在push时将顺序倒过来就可作为栈使用
class MyStack {
Queue<Integer>queone;
/** Initialize your data structure here. */
public MyStack() {
queone = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
int size = queone.size();
queone.offer(x);
for(int i=0;i<size;i++){
int temp = queone.poll();
queone.offer(temp);
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queone.poll();
}
/** Get the top element. */
public int top() {
return queone.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
if(queone.size()==0){
return true;
}else{
return false;
}
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/