Skip to content

Latest commit

 

History

History
114 lines (96 loc) · 2.22 KB

225.用队列实现栈.md

File metadata and controls

114 lines (96 loc) · 2.22 KB

225. 用队列实现栈

url

题目

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)

实现 MyStack 类:

  • void push(int x) 将元素x压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

方法

单队列的实现方法

code

js

let Mystack = function() {
    this.queue = [];
};
Mystack.prototype.push = function(x) {
    this.queue.push(x);
};
Mystack.prototype.pop = function() {
    return this.queue.pop()
};
Mystack.prototype.top = function() {
    return this.queue[this.queue.length - 1];
};

Mystack.prototype.empty = function() {
    return this.queue.length === 0;
};
var obj = new Mystack();
obj.push(1);
obj.push(2);
console.log(obj.pop());
console.log(obj.top());
console.log(obj.empty());

go

var q []int
func push1(x int) {
	q = append(q, x)
	cnt := len(q)
	for cnt > 1 {
		cnt--
		q = append(q, q[len(q) - 1])
	}
}
func pop1() int {
	q = q[0:len(q) - 1]
	return q[len(q) - 1]
}
func top1() int {
	return q[len(q) - 1]
}
func empty() bool {
	return len(q) == 0
}

java

class MyStack {
    private Queue<Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }
    /** Push element x onto stack. */
    public void push(int x) {
        queue.add(x);
        int cnt = queue.size();
        while (cnt-- > 1) {
            queue.add(queue.poll());
        }
    }
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.remove();
    }
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}
/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */