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

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

相关推荐
Cg136269159745 小时前
JS-对象-Dom案例
开发语言·前端·javascript
故事和你915 小时前
sdut-程序设计基础Ⅰ-实验五一维数组(8-13)
开发语言·数据结构·c++·算法·蓝桥杯·图论·类和对象
像污秽一样5 小时前
算法与设计与分析-习题4.2
算法·排序算法·深度优先·dfs·bfs
芯联智造6 小时前
【stm32简单外设篇】- WS2812单线地址式 RGB 灯带
c语言·stm32·单片机·嵌入式硬件
Jin、yz6 小时前
JAVA 八股
java·开发语言
我是唐青枫6 小时前
C#.NET Span 深入解析:零拷贝内存切片与高性能实战
开发语言·c#·.net
lxh01136 小时前
数据流的中位数
开发语言·前端·javascript
Storynone6 小时前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
盒马盒马7 小时前
Rust:迭代器
开发语言·后端·rust
明明如月学长7 小时前
AI 更新太快学不过来?我用OpenClaw打造专属AI学习工作流
算法