您的位置:首页 > 产品设计 > UI/UE

【Leetcode】Implement Queue using Stacks

2015-07-20 22:20 495 查看
【题目】

Implement the following operations of a queue using stacks.
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.
Notes:
You must use only standard operations of a stack -- which means only 
push
to top
peek/pop from top
size
,
and 
is empty
 operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

【思路】

I have one input stack, onto which I push the incoming elements, and one output stack, from which I peek/pop. I move elements from input stack to output stack when needed, i.e., when I need to peek/pop but the
output stack is empty. When that happens, I move all elements from input to output stack, thereby reversing the order so it's the correct order for peek/pop.

The loop in 
peek
 does the moving from input to output stack. Each element only ever
gets moved like that once, though, and only after we already spent time pushing it, so the overall amortized cost for each operation is O(1).
太巧妙了!
【代码】

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();
}
}


class MyQueue {
// Push element x to the back of queue.
private Stack<Integer> one = new Stack<>();
private Stack<Integer> two = new Stack<>();
private int count = 0;
public void push(int x) {
one.push(x);
count++;
}

// Removes the element from in front of queue.
public void pop() {
int tmp = 0;
if(empty()) return;
for(int i = 0 ; i<count - 1;i++){
tmp = one.pop();
two.push(tmp);
}
int result = one.pop();
while(!two.isEmpty()){
tmp = two.pop();
one.push(tmp);
}
count--;
}

// Get the front element.
public int peek() {
int tmp = 0;
if(empty()) return 0;
for(int i = 0 ; i<count - 1;i++){
tmp = one.pop();
two.push(tmp);
}
int result = one.peek();
while(!two.isEmpty()){
tmp = two.pop();
one.push(tmp);
}
return result;
}

// Return whether the queue is empty.
public boolean empty() {
return (count == 0);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode