无码av一区二区三区无码,在线观看老湿视频福利,日韩经典三级片,成 人色 网 站 欧美大片在线观看

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

225. 用隊列實現(xiàn)棧

2023-05-20 21:25 作者:薄荷硬糖醬  | 我要投稿

請你僅使用兩個隊列實現(xiàn)一個后入先出(LIFO)的棧,并支持普通棧的全部四種操作(push、top、pop 和 empty)。


實現(xiàn) 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

最多調(diào)用100 次 push、pop、top 和 empty

每次調(diào)用 pop 和 top 都保證棧不為空

?


進階:你能否僅用一個隊列來實現(xiàn)棧。


來源:力扣(LeetCode)

鏈接:https://leetcode.cn/problems/implement-stack-using-queues

著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。


前天寫的,只寫了使用兩個棧的寫法:

class?MyStack?{

public:

????queue<int>?first;

????queue<int>?second;

????MyStack()?{


????}

????

????void?push(int?x)?{

????????first.push(x);

????}

????

????int?pop()?{

????????int?size?=?first.size();

????????size--;

????????while(size--){

????????????second.push(first.front());

????????????first.pop();

????????}

????????int?ans?=?first.front();

????????first.pop();

????????first?=?second;

????????while(!second.empty()){

????????????second.pop();

????????}

????????return?ans;

????}

????

????int?top()?{

????????return?first.back();

????}

????

????bool?empty()?{

????????return?first.empty();

????}

};


225. 用隊列實現(xiàn)棧的評論 (共 條)

分享到微博請遵守國家法律
穆棱市| 蓝田县| 濮阳市| 东台市| 大渡口区| 正蓝旗| 太谷县| 太保市| 巴南区| 临朐县| 白山市| 宁南县| 宜阳县| 平罗县| 兖州市| 巴林左旗| 响水县| 富民县| 仙居县| 宣汉县| 方正县| 来宾市| 巴马| 乌拉特前旗| 祁东县| 康保县| 溧水县| 鲁甸县| 南雄市| 邳州市| 栖霞市| 化州市| 吴旗县| 平远县| 贺州市| 泽普县| 永顺县| 昭通市| 兴仁县| 大悟县| 龙岩市|