LeetCode 劍指offer 09.用兩個棧實現(xiàn)隊列
題目描述
用兩個棧實現(xiàn)一個隊列。隊列的聲明如下,請實現(xiàn)它的兩個函數(shù) appendTail 和 deleteHead ,分別完成在隊列尾部插入整數(shù)和在隊列頭部刪除整數(shù)的功能。(若隊列中沒有元素,deleteHead 操作返回 -1 )
這道題很簡單,主要理解棧與隊列的區(qū)別,注意細節(jié)就可以
題解
c++文章來源:http://www.zghlxwxcb.cn/news/detail-697919.html
class CQueue {
public:
stack<int> s1, s2;
CQueue() {
while (!s1.empty()) {
s1.pop();
}
while (!s2.empty()) {
s2.pop();
}
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
if (s2.empty()) {
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
if (s2.empty()) {
return -1;
} else {
int app = s2.top();
s2.pop();
return app;
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
Go文章來源地址http://www.zghlxwxcb.cn/news/detail-697919.html
type CQueue struct {
inStack, outStack []int
}
func Constructor() CQueue {
return CQueue{}
}
func (this *CQueue) AppendTail(value int) {
this.inStack = append(this.inStack, value)
}
func (this *CQueue) DeleteHead() int {
if len(this.outStack) == 0 {
if len(this.inStack) == 0 {
return -1
}
this.in2out()
}
value := this.outStack[len(this.outStack)-1]
this.outStack = this.outStack[:len(this.outStack)-1]
return value
}
func (this *CQueue) in2out() {
for len(this.inStack) > 0 {
this.outStack = append(this.outStack, this.inStack[len(this.inStack)-1])
this.inStack = this.inStack[:len(this.inStack)-1]
}
}
到了這里,關于LeetCode 劍指offer 09.用兩個棧實現(xiàn)隊列的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!