赞
踩
链接:. - 力扣(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);
- }

谢谢观看,希望对你有所帮助
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。