題目
??使用棧實(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
思路
請(qǐng)參考用兩個(gè)棧組成的隊(duì)列
代碼演示
package com.itz.stackAndQueue;
import java.util.Stack;
/**
* 使用棧實(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 操作)。
*
* 來(lái)源:力扣(LeetCode)
* 鏈接:https://leetcode-cn.com/problems/implement-queue-using-stacks
* 著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
*/
/**
* 執(zhí)行結(jié)果:
* 通過(guò)
* 顯示詳情
* 執(zhí)行用時(shí) :
* 0 ms
* , 在所有 java 提交中擊敗了
* 100.00%
* 的用戶(hù)
* 內(nèi)存消耗 :
* 34 MB
* , 在所有 java 提交中擊敗了
* 59.56%
* 的用戶(hù)
*/
public class MyQueue {
private Stack<Integer> stackPop;
private Stack<Integer> stackPush;
/** Initialize your data structure here. */
public MyQueue() {
this.stackPop = new Stack<>();
this.stackPush = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stackPush.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stackPop.isEmpty() && stackPush.isEmpty()){
throw new RuntimeException("隊(duì)列中沒(méi)有數(shù)據(jù)");
}
pushToPop();
return stackPop.pop();
}
/** Get the front element. */
public int peek() {
if (stackPop.isEmpty() && stackPush.isEmpty()){
throw new RuntimeException("隊(duì)列中沒(méi)有數(shù)據(jù)");
}
pushToPop();
return stackPop.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackPop.empty()&&stackPush.empty();
}
private void pushToPop(){
if (stackPop.isEmpty()){
while (!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
}
public static void main(String[] args) {
MyQueue obj = new MyQueue();
//obj.push(x);
int param_2 = obj.pop();
int param_3 = obj.peek();
boolean param_4 = obj.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
總結(jié)
該方法比較簡(jiǎn)單,分別通過(guò)棧和隊(duì)列的特點(diǎn)來(lái)實(shí)現(xiàn)的;時(shí)間復(fù)雜度和空間復(fù)雜度都是O(n)。
請(qǐng)參考用兩個(gè)棧組成的隊(duì)列