【一次过】Lintcode 493. 维护队列 II

实现一个双端队列

  1. push_front(item). 将新项添加到队列的前面。
  2. push_back(item). 将新项添加到队列的后面。
  3. pop_front(). 将第一个项移出队列,返回它。
  4. pop_back(). 将最后一项移出队列,返回它。

样例

例1:

输入:
push_front(1)
push_back(2)
pop_back() // return 2
pop_back() // return 1
push_back(3)
push_back(4)
pop_front() // return 3
pop_front() // return 4

例2:

输入:
push_front(1)
pop_front()// return 1

解题思路:

直接使用LinkedList数据结构。其中offer与poll是队列操作,对应题目的2,3.而1 4操作,只需根据字面意思调用接口,即offerFirst与pollLast

public class Dequeue {
    private LinkedList<Integer> deque = new LinkedList<>();
    
    public Dequeue() {
        // do intialization if necessary
    }

    /*
     * @param item: An integer
     * @return: nothing
     */
    public void push_front(int item) {
        // write your code here
        deque.offerFirst(item);
    }

    /*
     * @param item: An integer
     * @return: nothing
     */
    public void push_back(int item) {
        // write your code here
        deque.offer(item);
    }

    /*
     * @return: An integer
     */
    public int pop_front() {
        // write your code here
        return deque.poll();
    }

    /*
     * @return: An integer
     */
    public int pop_back() {
        // write your code here
        return deque.pollLast();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值