使用stack模擬佇列
阿新 • • 發佈:2018-11-11
232. Implement Queue using Stacks
用stack 實現佇列的基本功能,比如入隊(隊尾巴), 出隊(在隊頭出現佇列)
- s1作輸入棧,逐個元素壓棧,以此模擬佇列元素的入隊。直接入佇列即可
-
- 如果s2不為空的話,直接pop(),直接彈出來的情況
- 如果為空的話,需要將s1中的值進行轉過即可
==helper的功能就是將元素從s1移動到s2 ==
可以將helper程式碼放在peek中
將peek()和push()操作進行之前都需要進行
程式碼
push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
class MyQueue {
Stack<Integer> input = new Stack();
Stack<Integer> output = new Stack();
public void push(int x) {
input.push(x);
}
public void pop() {
peek();
output.pop();
}
public int peek() {
if (output.empty( ))
while (!input.empty())
output.push(input.pop());
return output.peek();
}
public boolean empty() {
return input.empty() && output.empty();
}
}
將helper程式碼抽象抽象出來
class MyQueue {
/** Initialize your data structure here. */
private Stack<Integer> in;
private Stack<Integer> out;
public MyQueue() {
in =new Stack<>();
out = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
helper();
return out.pop();
}
/** Get the front element. */
private void helper(){
if(out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
}
public int peek() {
//如果in中有元素的情況
//處理前面的元素, 如果
helper();
return out.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}