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

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

相关推荐
mit6.8242 小时前
bfs|栈
算法
tobebetter95272 小时前
How to manage python versions on windows
开发语言·windows·python
9***P3343 小时前
PHP代码覆盖率
开发语言·php·代码覆盖率
CoderYanger3 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz3 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗3 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java3 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*3 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
p***43483 小时前
Rust网络编程模型
开发语言·网络·rust
ᐇ9594 小时前
Java集合框架深度实战:构建智能教育管理与娱乐系统
java·开发语言·娱乐