一、題目大意
請你僅使用兩個佇列實作一個后入先出(LIFO)的堆疊,并支持普通堆疊的全部四種操作(push、top、pop 和 empty),
實作 MyStack 類:
void push(int x) 將元素 x 壓入堆疊頂,
int pop() 移除并回傳堆疊頂元素,
int top() 回傳堆疊頂元素,
boolean empty() 如果堆疊是空的,回傳 true ;否則,回傳 false ,
注意:
你只能使用佇列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 這些操作,
你所使用的語言也許不支持佇列, 你可以使用 list (串列)或者 deque(雙端佇列)來模擬一個佇列 , 只要是標準的佇列操作即可,
示例:
輸入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 2, 2, false]解釋:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 回傳 2
myStack.pop(); // 回傳 2
myStack.empty(); // 回傳 False
提示:
- 1 <= x <= 9
- 最多呼叫100 次 push、pop、top 和 empty
- 每次呼叫 pop 和 top 都保證堆疊不為空
進階:你能否僅用一個佇列來實作堆疊,
二、解題思路
使用佇列,每次把新加入的數插到前頭,這樣佇列保存的順序和堆疊的順序是相反的,它們的取出方式也是反的,那么反反得正,就是我們需要的順序了,我樣可以直接對佇列q操作,在隊尾加入了新元素x后,將x前面所有的元素都安排好順序取出并加到佇列到末尾,這樣下次就能直接取出x了,符合堆疊的后入先出的特性,其他三個操作也就是直接呼叫佇列的操作即可,
三、解題方法
3.1 Java實作
public class MyStack {
Queue<Integer> q;
public MyStack() {
// int size():獲取佇列長度;
//boolean add(E)/boolean offer(E):添加元素到隊尾;
//E remove()/E poll():獲取隊首元素并從佇列中洗掉;
//E element()/E peek():獲取隊首元素但并不從佇列中洗掉,
q = new LinkedList<>();
}
public void push(int x) {
q.add(x);
for (int i = 0; i < q.size() - 1; i++) {
q.add(q.poll());
}
}
public int pop() {
return q.poll();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
四、總結小記
- 2022/8/19 天氣就像大姑娘的臉呀,說變就變
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/502314.html
標籤:其他
