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

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

相关推荐
liu****2 小时前
笔试强训(六)
数据结构·c++·算法
SEO-狼术2 小时前
Stimulsoft Reports.JS 2025
开发语言·javascript·ecmascript
草莓工作室2 小时前
数据结构5:线性表5-循环链表
数据结构·循环链表
机器学习之心HML3 小时前
MATLAB基于GWO-BP神经网络对某拨叉件锻造金属流动性的参数分析
开发语言·神经网络·matlab
Cg136269159743 小时前
多态的定义
java·开发语言
weixin_46683 小时前
编程之python基础
开发语言·python
微信api接口介绍3 小时前
微信社群管理开发
java·开发语言·网络·微信
前端小刘哥3 小时前
超越“接收端”:解析视频推拉流EasyDSS在RTMP推流生态中的核心价值与中流砥柱作用
算法
csbysj20203 小时前
PHP 类型比较
开发语言
前端小刘哥3 小时前
新版视频直播点播平台EasyDSS用视频破局,获客转化双提升
算法