使用棧實(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 操作)。
分析
棧是先進(jìn)后出虐秋,隊(duì)列是先進(jìn)先出榕茧。要想用棧實(shí)現(xiàn)先進(jìn)先出,需要借助另外一個(gè)棧實(shí)現(xiàn)數(shù)據(jù)順序的轉(zhuǎn)換客给,轉(zhuǎn)換的時(shí)機(jī)是在壓入數(shù)據(jù)用押,且棧中數(shù)據(jù)不為空時(shí)。
import java.util.Stack;
/**
* 232. 用棧實(shí)現(xiàn)隊(duì)列
*/
public class MyQueue {
//存放于隊(duì)列相同特征的數(shù)據(jù)
Stack<Integer> s1;
//反轉(zhuǎn)數(shù)據(jù)的順序
Stack<Integer> s2;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if(s1.empty()){
s1.push(x);
return ;
}
while (!s1.empty()){
s2.push(s1.pop());
}
s2.push(x);
while(!s2.empty()){
s1.push(s2.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return s1.pop();
}
/** Get the front element. */
public int peek() {
return s1.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty();
}
}