Re: [閒聊] 每日LeetCode已回收
232. Implement Queue using Stacks
實作只用Stack來模擬Queue的行為。
Example:
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
思路:
1.就...資料結構課本裡面的東西,利用一個stack暫存頂層元素,拿到底層元素
之後再把剩餘元素放回原stack即可。
Java Code:
----------------------------------------
class MyQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
int n = s1.size();
for (int i = 0; i < n - 1; i++) {
s2.push(s1.pop());
}
int x = s1.pop();
for (int i = 0; i < n - 1; i++) {
s1.push(s2.pop());
}
return x;
}
public int peek() {
int n = s1.size();
for (int i = 0; i < n; i++) {
s2.push(s1.pop());
}
int x = s2.peek();
for (int i = 0; i < n; i++) {
s1.push(s2.pop());
}
return x;
}
public boolean empty() {
return s1.size() == 0;
}
}
----------------------------------------
--
https://i.imgur.com/sjdGOE3.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.89.30 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1671154225.A.755.html
→
12/16 09:30,
3年前
, 1F
12/16 09:30, 1F
→
12/16 09:30,
3年前
, 2F
12/16 09:30, 2F
→
12/16 09:31,
3年前
, 3F
12/16 09:31, 3F
→
12/16 09:31,
3年前
, 4F
12/16 09:31, 4F
推
12/16 09:32,
3年前
, 5F
12/16 09:32, 5F
推
12/16 09:43,
3年前
, 6F
12/16 09:43, 6F
→
12/16 09:49,
3年前
, 7F
12/16 09:49, 7F
推
12/16 09:51,
3年前
, 8F
12/16 09:51, 8F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 138 之 719 篇):