使用栈实现队列的下列操做:php
示例:数组
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false
说明:this
队列是先进先出,栈是先进后出。因此能够用两个栈,新元素压入栈的时候,先将栈中的元素弹出,放到另外一个栈中,把新元素压入到栈的底部,再把另外一个栈的元素弹出,放回原栈中。此时,栈顶元素就是出队时要先出的队首元素。
code
这里用的是数组表示队列,空间复杂度O(n),时间复杂度分 push 和 pop ,前者是O(n),后者是O(1)。blog
class MyQueue { /** * Initialize your data structure here. */ function __construct() { $this->stack1 = []; $this->stack2 = []; } /** * Push element x to the back of queue. * @param Integer $x * @return NULL */ function push($x) { while (!$this->empty()) { $this->stack2[] = array_pop($this->stack1); } $this->stack1[] = $x; while (!empty($this->stack2)) { $this->stack1[] = array_pop($this->stack2); } } /** * Removes the element from in front of queue and returns that element. * @return Integer */ function pop() { return array_pop($this->stack1); } /** * Get the front element. * @return Integer */ function peek() { return end($this->stack1); } /** * Returns whether the queue is empty. * @return Boolean */ function empty() { return empty($this->stack1) ? true :false; } }
使用两个栈,一个栈(stack1)仅负责入栈,一个栈(stack2)仅负责出栈。有新元素入队时,直接将元素压入 stack1 便可。但当出队时,须要判断 stack2 是否为空,若是为空,将 stack1 的元素依次出栈,压入 stack2 中,随后从 stack2 弹出,即为出队。但当 stack2 不为空时,仍然直接从 stack2 出栈便可,知道 stack2 为空时,才可将 stack1 的元素拿出来放入 stack2 中。
队列
这里用的是数组表示队列,空间复杂度O(n),时间复杂度分 push 和 pop ,前者是O(n),后者是O(1)。element
class MyQueue2 { /** * Initialize your data structure here. */ function __construct() { $this->stack1 = []; $this->stack2 = []; } /** * Push element x to the back of queue. * @param Integer $x * @return NULL */ function push($x) { $this->stack1[] = $x; } /** * Removes the element from in front of queue and returns that element. * @return Integer */ function pop() { if (empty($this->stack2)) { while (!empty($this->stack1)) { $this->stack2[] = array_pop($this->stack1); } } return array_pop($this->stack2); } /** * Get the front element. * @return Integer */ function peek() { if (empty($this->stack2)) { while (!empty($this->stack1)) { $this->stack2[] = array_pop($this->stack1); } } return end($this->stack2); } /** * Returns whether the queue is empty. * @return Boolean */ function empty() { return empty($this->stack1) && empty($this->stack2) ? true : false; } }