首页 > 其他 > 详细

leetcode - 使用栈实现队列的特性

时间:2019-10-28 09:31:19      阅读:79      评论:0      收藏:0      [点我收藏+]

使用栈实现队列的特性

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

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
    
```
MyQueue queue = new MyQueue();
    
queue.push(1);
queue.push(2);  
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false
```

说明:

你只能使用标准的栈操作 -- 也就是只有?push to top,?peek/pop from top,?size, 和?is empty?操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。


```
private Stack<Integer> in = new Stack<>();
private Stack<Integer> out = new Stack<>();
public static void main(String[] args) {
    // 使用栈实现队列的特性
    // 栈的特性是FILO, 队列的特性是FIFO, 所以使用栈实现队列的特性就需要使用两个栈来实现
    // 执行用时 :57 ms, 在所有 java 提交中击败了80.70%的用户
    //内存消耗 :34.1 MB, 在所有 java 提交中击败了53.06%的用户
    StackDemo obj = new StackDemo();
    obj.push(1);
    obj.push(2);
    System.out.println(obj.peek());
    System.out.println(obj.pop());
    System.out.println(obj.empty());
}

/** Initialize your data structure here. */
public StackDemo() {

}

/** Push element x to the back of queue. */
public void push(int x) {
    in.push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
    if(out.isEmpty()) {
        while(!in.isEmpty()) {
            out.push(in.pop());
        }
    }
    return out.pop();
}

/** Get the front element. */
public int peek() {
    if(out.isEmpty()) {
        while(!in.isEmpty()) {
            out.push(in.pop());
        }
    }
    return out.peek();
}

/** Returns whether the queue is empty. */
public boolean empty() {
    return out.isEmpty() && in.isEmpty();
}
```

leetcode - 使用栈实现队列的特性

原文:https://www.cnblogs.com/wadmwz/p/11750249.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!