数据结构---力扣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); 
}

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

相关推荐
爱喝热水的呀哈喽3 分钟前
非线性1无修
算法
贺函不是涵4 分钟前
【沉浸式求职学习day43】【Java面试题精选3】
java·开发语言·学习
xiaobin8899911 分钟前
matlab官方免费下载安装超详细教程2025最新matlab安装教程(MATLAB R2024b)
java·开发语言·其他·matlab
GG不是gg13 分钟前
数据结构:二叉树一文详解
数据结构·青少年编程
Takoony14 分钟前
正则表达式r前缀使用指南
开发语言·正则表达式·r语言
搏博20 分钟前
WPS中代码段的识别方法及JS宏实现
开发语言·javascript·wps
hjjdebug22 分钟前
c/c++数据类型转换.
c语言·c++·数据类型变换
vortex525 分钟前
Bash fork 炸弹 —— :(){ :|:& };:
运维·服务器·开发语言·网络安全·bash
花火QWQ27 分钟前
图论模板(部分)
c语言·数据结构·c++·算法·图论
Pacify_The_North42 分钟前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash