Skip to content

Instantly share code, notes, and snippets.

@wyukawa
Created March 29, 2019 02:22
Show Gist options
  • Save wyukawa/fa5e0b0de1dab3da85709951da459eba to your computer and use it in GitHub Desktop.
Save wyukawa/fa5e0b0de1dab3da85709951da459eba to your computer and use it in GitHub Desktop.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Node first;
private Node last;
private int size;
private class Node {
Item item;
Node prev;
Node next;
}
// construct an empty deque
public Deque() {
first = null;
last = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the deque
public int size() {
return size;
}
// add the item to the front
public void addFirst(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
if (isEmpty()) {
last = first;
} else {
first.next.prev = first;
}
size++;
}
// add the item to the end
public void addLast(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
if (isEmpty()) {
addFirst(item);
return;
}
Node oldlast = last;
last = new Node();
last.item = item;
last.prev = oldlast;
last.next = null;
last.prev.next = last;
size++;
}
// remove and return the item from the front
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item item = first.item;
if(size == 1) {
first = null;
last = null;
} else {
first = first.next;
first.prev = null;
}
size--;
return item;
}
// remove and return the item from the end
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item item = last.item;
if(size == 1) {
first = null;
last = null;
} else {
last = last.prev;
last.next = null;
}
size--;
return item;
}
// return an iterator over items in order from front to end
public Iterator<Item> iterator() {
return new DequeIterator();
}
private class DequeIterator implements Iterator<Item> {
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Item item = current.item;
current = current.next;
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment