日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

面试题 03.04. 化栈为队/面试题09. 用两个栈实现队列/232. 用栈实现队列

發(fā)布時(shí)間:2025/3/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 面试题 03.04. 化栈为队/面试题09. 用两个栈实现队列/232. 用栈实现队列 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

2020-05-08

1.題目描述

用兩個(gè)棧實(shí)現(xiàn)一個(gè)隊(duì)列

2.題解

將一個(gè)棧用來(lái)進(jìn)行入操作,另一個(gè)進(jìn)行出操作,入棧直接入,出棧的時(shí)候如果是空的則把另一個(gè) 棧中的所有元素移動(dòng)過(guò)來(lái),再進(jìn)行出棧,否則直接出棧即可。

3.代碼

面試題 03.04.

class MyQueue { public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {s1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {if (s2.empty()){while (!s1.empty()){int t=s1.top();s1.pop();s2.push(t);}}int r=s2.top();s2.pop();return r;}/** Get the front element. */int peek() {if (s2.empty()){while (!s1.empty()){int t=s1.top();s1.pop();s2.push(t);}}return s2.top();}/** Returns whether the queue is empty. */bool empty() {if (s1.empty()&&s2.empty()) return true;return false;}stack<int> s1,s2;// s1專門(mén)用來(lái)入棧,s2專門(mén)用來(lái)出棧 };/*** 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();* bool param_4 = obj->empty();*/

面試題09.

class CQueue { public:CQueue() {}void appendTail(int value) {s1.push(value);}int deleteHead() {if (s1.empty()&&s2.empty()) return -1;if (s2.empty()){while (!s1.empty()){s2.push(s1.top());s1.pop();}}int t=s2.top();s2.pop();return t;}stack<int> s1,s2; };/*** Your CQueue object will be instantiated and called as such:* CQueue* obj = new CQueue();* obj->appendTail(value);* int param_2 = obj->deleteHead();*/
  • class MyQueue { public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {s1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {if (s2.empty()){while (!s1.empty()){s2.push(s1.top());s1.pop();}}int t=s2.top();s2.pop();return t;}/** Get the front element. */int peek() {if (s2.empty()){while (!s1.empty()){s2.push(s1.top());s1.pop();}}return s2.top();}/** Returns whether the queue is empty. */bool empty() {if (s1.empty()&&s2.empty()) return true;return false;}stack<int>s1,s2; };/*** 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();* bool param_4 = obj->empty();*/

    總結(jié)

    以上是生活随笔為你收集整理的面试题 03.04. 化栈为队/面试题09. 用两个栈实现队列/232. 用栈实现队列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。