forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deque.java
100 lines (83 loc) · 2.04 KB
/
deque.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* This is a doubly linked list where each node has a previous or next pointer.
It allows adding and deleting of the first and last node.
*/
public class Deque<Item> {
private int size;
private Node first;
private Node last;
private class Node {
Item item;
Node prev;
Node next;
}
public Deque() {
first = null;
last = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void addFirst(Item item) {
if (item == null) {
throw new IllegalArgumentException("Item added to front is null");
}
Node oldFirst = first;
first = new Node();
first.item = item;
first.prev = null;
first.next = oldFirst;
size++;
// link next node to first node, if next node has data
if (first.next != null) {
oldFirst.prev = first;
}
if (size == 1) {
last = first;
} else if (size == 2) {
// this equal last node
last = oldFirst;
}
}
public void addLast(Item item) {
if (item == null) {
throw new IllegalArgumentException("Item added to end is null");
}
Node oldLast = last;
last = new Node();
last.item = item;
last.prev = oldLast;
last.next = null;
size++;
// link prev node to last node, if prev node has data
if (last.prev != null) {
oldLast.next = last;
}
if (size == 1) {
first = last;
} else if (size == 2) {
// this equal last node
first = oldLast;
}
}
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
Item item = first.item;
first = first.next;
size--;
return item;
}
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException("Deque is empty");
}
Item item = last.item;
last = last.prev;
size--;
return item;
}