225. 用栈实现队列
需要注意:实现peek时不能调用pop()方法,否则会打乱原队列顺序
class MyQueue {
Stack<Integer> stack;
Stack<Integer> tmp;
public MyQueue() {
stack = new Stack<>();
tmp = new Stack<>();
}
public void push(int x) {
stack.push(x);
}
public int pop() {
if (stack.size() == 1) return stack.pop();
while(stack.size() > 1) tmp.push(stack.pop());
int popped = stack.pop();
while(!tmp.isEmpty()) stack.push(tmp.pop());
return popped;
}
public int peek() {
if (stack.size() == 1) return stack.peek();
while(stack.size() > 1) tmp.push(stack.pop());
int topElement = stack.peek();
while(!tmp.isEmpty()) stack.push(tmp.pop());
return topElement;
}
public boolean empty() {
return stack.isEmpty();
}
}
225. 用队列实现栈
可使用一个队列实现
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
}
public int pop() {
if (queue.size() == 1) return queue.poll();
int n = queue.size() - 1;
for (int i = 0; i < n; i++){
queue.offer(queue.poll());
}
return queue.poll();
}
public int top() {
int topElement = pop();
queue.offer(topElement);
return topElement;
}
public boolean empty() {
return queue.isEmpty();
}
}
待研究:
为什么LeetCode中:
Stack的实现方法是Stack<T> stack = new Stack<>()
Queue的实现方法是Queue<T> queue = new LinkedList<>()