0301-用队列实现栈

用队列实现栈

题目卡片

思路

这题我用到的是Deque 。Deque就是double ended queue,双端队列,可以在首尾插入或删除元素。

当把deque看作栈(元素都在队头进行操作)

  • push(x) -- addFirst(x) -- 元素 x 入栈

  • pop() -- removeFirst() -- 移除栈顶元素

  • top() -- peekFirst() -- 获取栈顶元素

  • empty() -- isEmpty() -- 返回栈是否为空

代码

class MyStack {

    Deque<Integer> mydeque;
    public MyStack() {
        mydeque = new LinkedList<>();
    }
    
    public void push(int x) {
        mydeque.addFirst(x);
    }
    
    public int pop() {
        return mydeque.pop();
    }
    
    public int top() {
        return mydeque.peekFirst();
    }
    
    public boolean empty() {
        return mydeque.isEmpty();
    }
}

扩展

Queue和Deque都是继承于Collection。Deque是Queue的子接口。

  1. 当把deque看作栈(元素都在队头进行操作)
  2. 当把deque看作队列(元素在一端进队,另一端出队)

官方文档

A linear collection that supports element insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck". Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or *false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted* Queue** implementations; in most implementations, insert operations cannot fail.

猜你喜欢

转载自www.cnblogs.com/Nick17t/p/12462579.html