[LeetCode] 225. Implement Stack using Queues

用队列实现栈。题干即是题意,这一题跟之前的232题一样,需要实现几个queue的函数。例子,

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

这一题只需要用到一个队列。因为是JS的关系所以这一题会好做很多,因为在JS里面,栈和队列都是用数组实现的。依然解释一下几个函数的实现方式。

push(x) - 将元素推进栈。时间均摊O(n),因为涉及到会扩大内存的动作。
pop() -- 将栈顶元素弹出。时间O(1)
top() -- 等同于peek,看一下栈顶元素是什么。时间O(1)
empty() -- 判断栈是否为空。时间O(1)

JavaScript实现

 1 /**
 2  * Initialize your data structure here.
 3  */
 4 var MyStack = function () {
 5     this.stack = [];
 6 };
 7 
 8 /**
 9  * Push element x onto stack. 
10  * @param {number} x
11  * @return {void}
12  */
13 MyStack.prototype.push = function (x) {
14     this.stack[this.stack.length] = x;
15 };
16 
17 /**
18  * Removes the element on top of the stack and returns that element.
19  * @return {number}
20  */
21 MyStack.prototype.pop = function () {
22     let res = this.stack[this.stack.length - 1];
23     this.stack.length = this.stack.length - 1;
24     return res;
25 };
26 
27 /**
28  * Get the top element.
29  * @return {number}
30  */
31 MyStack.prototype.top = function () {
32     return this.stack[this.stack.length - 1];
33 };
34 
35 /**
36  * Returns whether the stack is empty.
37  * @return {boolean}
38  */
39 MyStack.prototype.empty = function () {
40     return this.stack.length === 0;
41 };
42 
43 /**
44  * Your MyStack object will be instantiated and called as such:
45  * var obj = new MyStack()
46  * obj.push(x)
47  * var param_2 = obj.pop()
48  * var param_3 = obj.top()
49  * var param_4 = obj.empty()
50  */

Java实现

 1 class MyStack {
 2     Queue<Integer> queue;
 3     /** Initialize your data structure here. */
 4     public MyStack() {
 5         queue = new LinkedList<>();
 6     }
 7     
 8     /** Push element x onto stack. */
 9     public void push(int x) {
10         queue.add(x);
11         for (int i = 0; i < queue.size() - 1; i++) {
12             queue.add(queue.poll());
13         }
14     }
15     
16     /** Removes the element on top of the stack and returns that element. */
17     public int pop() {
18         return queue.poll();
19     }
20     
21     /** Get the top element. */
22     public int top() {
23         return queue.peek();
24     }
25     
26     /** Returns whether the stack is empty. */
27     public boolean empty() {
28         return queue.isEmpty();
29     }
30 }
31 
32 /**
33  * Your MyStack object will be instantiated and called as such:
34  * MyStack obj = new MyStack();
35  * obj.push(x);
36  * int param_2 = obj.pop();
37  * int param_3 = obj.top();
38  * boolean param_4 = obj.empty();
39  */

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12407764.html