用兩個(gè)棧實(shí)現(xiàn)一個(gè)隊(duì)列蝙寨。隊(duì)列的聲明如下晒衩,請實(shí)現(xiàn)它的兩個(gè)函數(shù) appendTail 和 deleteHead ,分別完成在隊(duì)列尾部插入整數(shù)和在隊(duì)列頭部刪除整數(shù)的功能墙歪。(若隊(duì)列中沒有元素听系,deleteHead 操作返回 -1 )
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán)虹菲,非商業(yè)轉(zhuǎn)載請注明出處靠胜。
思路一:雙棧
將一個(gè)棧當(dāng)作輸入棧,用于壓入appendTail傳入的數(shù)據(jù)毕源;另一個(gè)棧當(dāng)作輸出棧浪漠,用于deleteHead操作。
每次deleteHead時(shí)脑豹,若輸出棧為空則將輸入棧的全部數(shù)據(jù)依次彈出并壓入輸出棧郑藏,這樣輸出棧從棧頂往棧底的順序就是隊(duì)列從隊(duì)首往隊(duì)尾的順序。
class CQueue {
public:
CQueue() {
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
if (s1.empty())
return -1;
int res = 0;
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
res = s2.top();
s2.pop();
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
return res;
}
private:
stack<int> s1;
stack<int> s2;
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/