layout: posttitle: PHP 用栈实现队列
subtitle: PHP 用栈实现队列
date: 2020-05-04
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode
- 用栈实现队列

用栈实现队列

题干:使用栈实现队列的下列操作:

  • push(x) — 将一个元素放入队列的尾部。
  • pop() — 从队列首部移除元素。
  • peek() — 返回队列首部的元素。
  • empty() — 返回队列是否为空。
    示例:
  1. MyQueue queue = new MyQueue();
  2. queue.push(1);
  3. queue.push(2);
  4. queue.peek(); // 返回 1
  5. queue.pop(); // 返回 1
  6. queue.empty(); // 返回 false

说明:

你只能使用标准的栈操作 — 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks

解题思路

定义两个栈,一个输入栈,一个输出栈,输入栈保存输入的内容,然后输出栈是输入栈逆序之后的数据,输出栈直接采用正常栈的操作就行,反正已经逆序了。

PHP 实现

  1. class MyQueue {
  2. private $inStack;
  3. private $outStack;
  4. /**
  5. * Initialize your data structure here.
  6. */
  7. function __construct() {
  8. $this->inStack = new SplStack();
  9. $this->outStack = new SplStack();
  10. }
  11. /**
  12. * Push element x to the back of queue.
  13. * @param Integer $x
  14. * @return NULL
  15. */
  16. function push($x) {
  17. $this->inStack->push($x);
  18. }
  19. /**
  20. * Removes the element from in front of queue and returns that element.
  21. * @return Integer
  22. */
  23. function pop() {
  24. if ($this->outStack->isEmpty()) {
  25. $this->shift();
  26. }
  27. return $this->outStack->pop();
  28. }
  29. /**
  30. * Get the front element.
  31. * @return Integer
  32. */
  33. function peek() {
  34. if ($this->outStack->isEmpty()) {
  35. $this->shift();
  36. }
  37. return $this->outStack->top();
  38. }
  39. private function shift()
  40. {
  41. while (!$this->inStack->isEmpty()) {
  42. $this->outStack->push($this->inStack->pop());
  43. }
  44. }
  45. /**
  46. * Returns whether the queue is empty.
  47. * @return Boolean
  48. */
  49. function empty() {
  50. return $this->inStack->isEmpty() && $this->outStack->isEmpty();
  51. }
  52. }
  53. /**
  54. * Your MyQueue object will be instantiated and called as such:
  55. * $obj = MyQueue();
  56. * $obj->push($x);
  57. * $ret_2 = $obj->pop();
  58. * $ret_3 = $obj->peek();
  59. * $ret_4 = $obj->empty();
  60. */

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券