用棧實(shí)現(xiàn)隊(duì)列
題目
使用棧實(shí)現(xiàn)隊(duì)列的下列操作:
push(x) -- 將一個(gè)元素放入隊(duì)列的尾部。
pop() -- 從隊(duì)列首部移除元素窿侈。
peek() -- 返回隊(duì)列首部的元素霎箍。
empty() -- 返回隊(duì)列是否為空未斑。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
說(shuō)明:
你只能使用標(biāo)準(zhǔn)的棧操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的僵蛛。
你所使用的語(yǔ)言也許不支持棧。你可以使用 list 或者 deque(雙端隊(duì)列)來(lái)模擬一個(gè)棧侵浸,只要是標(biāo)準(zhǔn)的棧操作即可寨闹。
假設(shè)所有操作都是有效的 (例如,一個(gè)空的隊(duì)列不會(huì)調(diào)用 pop 或者 peek 操作)挂谍。
思路
創(chuàng)建兩個(gè)stack inStack outStack
入隊(duì): 將 outStack 元素遍歷,彈出棧頂元素 到 inStack, 在 inStack push進(jìn)入新元素
出隊(duì): 將 instack 元素遍歷,彈出棧頂元素 到 outStack , 取出 outStack棧頂元素即可
Java實(shí)現(xiàn)
public class _232_用棧實(shí)現(xiàn)隊(duì)列 {
/** Initialize your data structure here. */
public Stack<Integer> inStack = new Stack<>();
public Stack<Integer> outStack = new Stack<>();
public MyQueue() {
}
/** 入隊(duì) */
public void push(int x) {
while (!outStack.isEmpty()) {
inStack.push(outStack.pop());
}
inStack.push(x);
}
/** 從隊(duì)列首部移除元素 */
public int pop() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.pop();
}
/** 返回隊(duì)列首部的元素 */
public int peek() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.peek();
}
/** 返回隊(duì)列是否為空 */
public boolean empty() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
return outStack.isEmpty();
}
}
Swift實(shí)現(xiàn)
class Test232 {
var inStack = [Int]()
var outStack = [Int]()
/** Initialize your data structure here. */
init() {
}
/** Push element x to the back of queue. */
func push(_ x: Int) {
while outStack.count > 0 {
inStack.append(outStack.popLast()!)
}
inStack.append(x)
}
/** Removes the element from in front of queue and returns that element. */
func pop() -> Int {
while inStack.count > 0 {
outStack.append(inStack.popLast()!)
}
return outStack.popLast()!
}
/** Get the front element. */
func peek() -> Int {
while inStack.count > 0 {
outStack.append(inStack.popLast()!)
}
return outStack[outStack.count - 1]
}
/** Returns whether the queue is empty. */
func empty() -> Bool {
while inStack.count > 0 {
outStack.append(inStack.popLast()!)
}
return outStack.count > 0 ? false : true
}
}