列表

详情


面试题 03.04. 化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。


示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false


说明:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class MyQueue { public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { } /** Removes the element from in front of queue and returns that element. */ int pop() { } /** Get the front element. */ int peek() { } /** Returns whether the queue is empty. */ bool empty() { } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */

golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2021-06-10 16:46:50

type MyQueue struct {
    stack []int
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    return MyQueue{stack: []int{}}
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    this.stack = append(this.stack, x)
}


/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    t := this.stack[0]
    this.stack = this.stack[1:]
    return t
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
    return this.stack[0]
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
    return len(this.stack) == 0
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */

上一题