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

用队列实现栈

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

  • push(x) — 元素 x 入栈

  • pop() — 移除栈顶元素

  • top() — 获取栈顶元素

  • empty() — 返回栈是否为空
    注意:

  • 你只能使用队列的基本操作— 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。

  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

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

解题思路

和用栈实现队列一样的,一个队列负责入,一个队列负责出,入队列接收参数之后,倒序将参数压入出队列,因为php splqueue 标准库有top,pop这样的方放,也可以直接使用,方便快捷。

额外:以下的代码执行用时和内存消耗打败了100%的玩家,可能PHP提交较少。

PHP 实现

  1. class MyStack {
  2. private $inQueue;
  3. private $outQueue;
  4. /**
  5. * Initialize your data structure here.
  6. */
  7. function __construct() {
  8. $this->inQueue = new SplQueue();
  9. $this->outQueue = new SplQueue();
  10. }
  11. /**
  12. * Push element x onto stack.
  13. * @param Integer $x
  14. * @return NULL
  15. */
  16. function push($x) {
  17. $this->inQueue->enqueue($x);
  18. while (!$this->inQueue->isEmpty()) {
  19. $this->outQueue->enqueue($this->inQueue->dequeue());
  20. }
  21. }
  22. /**
  23. * Removes the element on top of the stack and returns that element.
  24. * @return Integer
  25. */
  26. function pop() {
  27. return $this->outQueue->pop();
  28. }
  29. /**
  30. * Get the top element.
  31. * @return Integer
  32. */
  33. function top() {
  34. return $this->outQueue->top();
  35. }
  36. /**
  37. * Returns whether the stack is empty.
  38. * @return Boolean
  39. */
  40. function empty() {
  41. return $this->outQueue->isEmpty();
  42. }
  43. }
  44. /**
  45. * Your MyStack object will be instantiated and called as such:
  46. * $obj = MyStack();
  47. * $obj->push($x);
  48. * $ret_2 = $obj->pop();
  49. * $ret_3 = $obj->top();
  50. * $ret_4 = $obj->empty();
  51. */

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