数据结构---力扣232.用栈实现队列(C

链接:. - 力扣(LeetCode)【点击即可跳转】

思路:

栈 是 后进先出

队列 是 先进先出


让一个栈(s1)作为空栈,入队列的栈

另一个(s2)作为非空栈,出队列的栈

假设 1.2.3.4

入s1: (4.3.2.1)

从s1进到s2: (1.2.3.4)

代码中 栈 的基本实现,不在以下展示,参考之前的文章。

以下为函数的具体实现:

复制代码
typedef struct 
{
    ST s1; // 入队列的栈
    ST s2; // 出队列的栈
} MyQueue;

MyQueue* myQueueCreate()
{
    MyQueue* QStack = (MyQueue*)malloc(sizeof(MyQueue));
    StackInit(&QStack->s1);
    StackInit(&QStack->s2);
    return QStack;
}
void myQueuePush(MyQueue* obj, int x)
{
    assert(obj);
    StackPush(&obj->s1, x);
}
int myQueuePop(MyQueue* obj)
 {
    if (StackEmpty(&obj->s2)) 
    {
        while (obj->s1.size > 0) 
        {
         StackPush(&obj->s2, StackTop(&obj->s1));
         StackPop(&obj->s1);
        }
    }
    assert(obj);
    int ret = StackTop(&obj->s2);
    StackPop(&obj->s2);
    return ret;
}

int myQueuePeek(MyQueue* obj)
 {
    if (StackEmpty(&obj->s2)) 
{
      while (obj->s1.size > 0)
    {
     StackPush(&obj->s2, StackTop(&obj->s1));
    StackPop(&obj->s1);
    }
}
    assert(obj);
    int ret = StackTop(&obj->s2);
    return ret;
}

bool myQueueEmpty(MyQueue* obj)
{
    return StackEmpty(&obj->s2) && StackEmpty(&obj->s1);
}

void myQueueFree(MyQueue* obj) 
{ 
    free(obj); 
}

谢谢观看,希望对你有所帮助

相关推荐
future141213 分钟前
C#学习日记
开发语言·学习·c#
king_harry29 分钟前
Java程序-OceanBase Connector/J 示例
开发语言
martian6651 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习1 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法
SuperW1 小时前
数据结构——队列
数据结构
傻啦嘿哟1 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
翻滚吧键盘1 小时前
js代码09
开发语言·javascript·ecmascript
q567315231 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
??tobenewyorker2 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
蓝澈11212 小时前
迪杰斯特拉算法之解决单源最短路径问题
java·数据结构