public interface MyDeque<E>{
boolean offerFirst(E e);
boolean offerLast(E e);
E pollFirst();
E pollLast();
E peekFirst();
E peekLast();
boolean isEmpty();
boolean isFull();
}
(2). 模拟双端队列
//双向链表模拟双端队列
public class MyLinkedList<E> implements MyDeque<E>, Iterable<E> {
//Node内部类
private static class Node<E> {
Node<E> prev;
E value;
Node<E> next;
public Node(Node<E> prev, E value, Node<E> next) {
this.prev = prev;
this.value = value;
this.next = next;
}
}
//哨兵节点
Node<E> sential = new Node<>(null, null, null);
//双端队列的容量
private int capacity;
//双端队列的实际大小
private int size;
public MyLinkedList(int capacity) {
this.capacity = capacity;
sential.prev = sential;
sential.next = sential;
}
@Override
public boolean offerFirst(E e) {
//如果双端队列已经满了, 加入失败
if(isFull()) {
return false;
}
Node<E> p = new Node<>(sential, e, sential.next);
sential.next = p;
size++;
return true;
}
@Override
public boolean offerLast(E e) {
if(isFull()) {
return false;
}
Node<E> p = new Node<>(sential.prev, e, sential);
Node<E> q = sential.prev;
q.next = p;
sential.prev = p;
size++;
return true;
}
@Override
public E pollFirst() {
//如果双端队列已空
if (isEmpty()) {
return null;
}
Node<E> p = sential.next;
sential.next = p.next;
p.next.prev = sential;
size--;
return p.value;
}
@Override
public E pollLast() {
if(isEmpty()) {
return null;
}
Node<E> p = sential.prev;
Node<E> q = p.prev;
q.next = sential;
sential.prev = q;
size--;
return p.value;
}
@Override
public E peekFirst() {
if (isEmpty()) {
return null;
}
return sential.next.value;
}
@Override
public E peekLast() {
if(isEmpty()) {
return null;
}
return sential.prev.value;
}
@Override
public boolean isEmpty() {
//当head与tail指针都指向了哨兵节点时, 此时双端队列为空
return size == 0;
}
@Override
public boolean isFull() {
return size > capacity;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
Node<E> p = sential.next;
@Override
public boolean hasNext() {
return p != sential;
}
@Override
public E next() {
E value = p.value;
p = p.next;
return value;
}
};
}
}
3. 单元测试
public class MyLinkedListTest {
@Test
public void test1() {
MyLinkedList<Integer> deque = new MyLinkedList<>(10);
deque.offerFirst(1);
deque.offerFirst(2);
deque.offerFirst(3);
deque.offerFirst(4);
deque.offerFirst(5);
deque.offerFirst(6);
for (Integer element : deque) {
System.out.print(element + " ");
}
//6 5 4 3 2 1
}
@Test
public void test2() {
MyLinkedList<Integer> deque = new MyLinkedList<>(10);
deque.offerLast(1);
deque.offerLast(2);
deque.offerLast(3);
deque.offerLast(4);
deque.offerLast(5);
deque.offerLast(6);
for(Integer element : deque) {
System.out.print(element + " ");
}
System.out.println();
//1 2 3 4 5 6
System.out.println(deque.pollFirst());
//1
System.out.println(deque.pollFirst());
//2
System.out.println(deque.pollLast());
//6
System.out.println(deque.peekFirst());
//3
}
}