LeetCode 剑指offer 09.用两个栈实现队列

LeetCode 剑指offer 09.用两个栈实现队列

题目描述

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

这道题很简单,主要理解栈与队列的区别,注意细节就可以

题解

c++

cpp 复制代码
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

cpp 复制代码
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]
    }
}
相关推荐
Blue.ztl44 分钟前
DP刷题练习(二)
算法·cpp
青山是哪个青山1 小时前
位运,模拟,分治,BFS,栈和哈希表
算法·散列表·宽度优先
Zephyrtoria3 小时前
区间合并:区间合并问题
java·开发语言·数据结构·算法
柏箱5 小时前
容器里有10升油,现在只有两个分别能装3升和7升油的瓶子,需要将10 升油等分成2 个5 升油。程序输出分油次数最少的详细操作过程。
算法·bfs
Hello eveybody6 小时前
C++介绍整数二分与实数二分
开发语言·数据结构·c++·算法
Mallow Flowers8 小时前
Python训练营-Day31-文件的拆分和使用
开发语言·人工智能·python·算法·机器学习
GalaxyPokemon9 小时前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
leo__5209 小时前
matlab实现非线性Granger因果检验
人工智能·算法·matlab
GG不是gg9 小时前
位运算详解之异或运算的奇妙操作
算法
FF-Studio11 小时前
万物皆数:构建数字信号处理的数学基石
算法·数学建模·fpga开发·自动化·音视频·信号处理·dsp开发