当前位置 博文首页 > 棒棒的小笨笨的博客:LeetCode 232.用栈实现队列----Java图解
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
说明:
你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
目的:栈的存储和队列的存储的最终顺序一样
思路:用两个栈进行调换
1.定义一个临时栈temp_stack
2.定义一个最终栈final_stack
第一步:1—>temp_stack
public void push(int x) {
while(!temp_stack.isEmpty()) {
final_stack.add(temp_stack.peek());
temp_stack.pop();
}
temp_stack.add(x);
while(!final_stack.isEmpty()) {
temp_stack.add(final_stack.peek());
final_stack.pop();
}
}
第二步:2—>temp_stack
以此类推
class MyQueue {
Stack<Integer> final_stack;//最终栈
Stack<Integer> temp_stack;//临时栈
//思路:用一个临时栈来存储并调换
/** Initialize your data structure here. */
public MyQueue() {
final_stack = new Stack<Integer>();
temp_stack = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!temp_stack.isEmpty()) {
final_stack.add(temp_stack.peek());
temp_stack.pop();
}
temp_stack.add(x);
while(!final_stack.isEmpty()) {
temp_stack.add(final_stack.peek());
final_stack.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while (!final_stack.empty())
{
temp_stack.push(final_stack.peek());
final_stack.pop();
}
int temp = temp_stack.peek();
temp_stack.pop();
return temp;
}
/** Get the front element. */
public int peek() {
while (!final_stack.empty())
{
temp_stack.push(final_stack.peek());
final_stack.pop();
}
int temp1 = temp_stack.peek();
return temp1;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return temp_stack.isEmpty();
}
}
如有时间,还会优化,仔细解析,如有疑问,请留言。
cs