-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeque.java
More file actions
150 lines (121 loc) · 2.44 KB
/
Deque.java
File metadata and controls
150 lines (121 loc) · 2.44 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import java.util.Iterator;
public class Deque<Item> implements Iterable<Item> {
private class Node {
public Item value;
Node prev;
Node next;
}
private class ListIterator implements Iterator<Item> {
private Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
Item ret = current.value;
current = current.next;
return ret;
}
}
private Node head;
private Node tail;
private int count;
// construct an empty deque
public Deque() {
count = 0;
head = null;
tail = null;
}
// is the deque empty?
public boolean isEmpty() {
return count == 0;
}
// return the number of items on the deque
public int size() {
return count;
}
// add the item to the front
public void addFirst(Item item) {
if (item == null) {
throw new java.lang.IllegalArgumentException();
}
Node node = new Node();
node.value = item;
Node p = head;
head = node;
head.next = p;
if (p != null) {
p.prev = head;
} else {
tail = head;
}
count++;
}
// add the item to the end
public void addLast(Item item) {
if (item == null) {
throw new java.lang.IllegalArgumentException();
}
Node node = new Node();
node.value = item;
Node p = tail;
tail = node;
tail.prev = p;
if (p != null) {
p.next = tail;
} else {
head = tail;
}
count++;
}
// remove and return the item from the front
public Item removeFirst() {
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
count--;
Node first = head;
head = head.next;
if (head == null) {
tail = null;
} else {
head.prev = null;
}
return first.value;
}
// remove and return the item from the end
public Item removeLast() {
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
count--;
Node last = tail;
tail = tail.prev;
if (tail == null) {
head = null;
} else {
tail.next = null;
}
return last.value;
}
// return an iterator over items in order from front to end
public Iterator<Item> iterator() {
return new ListIterator();
}
// unit testing (optional)
public static void main(String[] args) {
Deque<Integer> s = new Deque<Integer>();
s.addFirst(1);
s.addLast(2);
s.removeFirst();
s.removeLast();
Iterator<Integer> iter = s.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}