当前位置:   article > 正文

数据结构---力扣232.用栈实现队列(C

数据结构---力扣232.用栈实现队列(C

链接:. - 力扣(LeetCode)【点击即可跳转】

思路:

栈     是  后进先出

队列 是  先进先出


让一个栈(s1)作为空栈,入队列的栈

另一个(s2)作为非空栈,出队列的栈

假设 1.2.3.4

           入s1: (4.3.2.1)

从s1进到s2: (1.2.3.4)

代码中 栈 的基本实现,不在以下展示,参考之前的文章。

以下为函数的具体实现:

  1. typedef struct
  2. {
  3. ST s1; // 入队列的栈
  4. ST s2; // 出队列的栈
  5. } MyQueue;
  6. MyQueue* myQueueCreate()
  7. {
  8. MyQueue* QStack = (MyQueue*)malloc(sizeof(MyQueue));
  9. StackInit(&QStack->s1);
  10. StackInit(&QStack->s2);
  11. return QStack;
  12. }
  13. void myQueuePush(MyQueue* obj, int x)
  14. {
  15. assert(obj);
  16. StackPush(&obj->s1, x);
  17. }
  18. int myQueuePop(MyQueue* obj)
  19. {
  20. if (StackEmpty(&obj->s2))
  21. {
  22. while (obj->s1.size > 0)
  23. {
  24. StackPush(&obj->s2, StackTop(&obj->s1));
  25. StackPop(&obj->s1);
  26. }
  27. }
  28. assert(obj);
  29. int ret = StackTop(&obj->s2);
  30. StackPop(&obj->s2);
  31. return ret;
  32. }
  33. int myQueuePeek(MyQueue* obj)
  34. {
  35. if (StackEmpty(&obj->s2))
  36. {
  37. while (obj->s1.size > 0)
  38. {
  39. StackPush(&obj->s2, StackTop(&obj->s1));
  40. StackPop(&obj->s1);
  41. }
  42. }
  43. assert(obj);
  44. int ret = StackTop(&obj->s2);
  45. return ret;
  46. }
  47. bool myQueueEmpty(MyQueue* obj)
  48. {
  49. return StackEmpty(&obj->s2) && StackEmpty(&obj->s1);
  50. }
  51. void myQueueFree(MyQueue* obj)
  52. {
  53. free(obj);
  54. }

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/707977
推荐阅读
相关标签
  

闽ICP备14008679号