实现一个双端队列
push_front(item)
. 将新项添加到队列的前面。push_back(item)
. 将新项添加到队列的后面。pop_front()
. 将第一个项移出队列,返回它。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();
}
}