本来我是使用单链表实现的(queue)但是总是报超时,没办法我只能使用了双向链表deque
java
public class MyStack {
/**
* Initialize your data structure here.
*/
private Deque<Integer> queue;
;
public MyStack() {
// 向上转型
queue = new LinkedList<Integer>();
}
/**
* Push element x onto stack.
*/
public void push(int x) {
queue.offer(x);
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
//把queue里面的数据逐渐放入到help中,同时剩余一个在queue中, 之后把最后一个给删除就是pop了。
if (!queue.isEmpty()) {
int temp = queue.getLast();
queue.removeLast();
return temp;
}
else throw new RuntimeException("error");
}
/**
* Get the top element.
*/
public int top() {
return queue.getLast();
}
/**
* Returns whether the stack is empty.
*/
public boolean empty() {
return queue.isEmpty();
}
}