-
Notifications
You must be signed in to change notification settings - Fork 1
/
Deque.java
147 lines (122 loc) · 3.23 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
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
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
public class Deque<Item> implements Iterable<Item> {
private class Node {
Item data;
Node next;
public Node(Item d) {
data = d;
next = null;
}
}
private class DequeIterator implements Iterator<Item> {
private Node current = first;
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return current != null;
}
public Item next() {
if (current == null) {
throw new NoSuchElementException();
}
Item item = current.data;
current = current.next;
return item;
}
}
private Node first;
private Node last;
private int size;
public Deque() {
first = null;
last = null;
size = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return size;
}
public void addFirst(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
Node temp = new Node(item);
if (isEmpty()) {
last = temp;
} else {
temp.next = first;
}
first = temp;
size++;
}
public void addLast(Item item) {
if (item == null) {
throw new IllegalArgumentException();
}
Node temp = new Node(item);
if (isEmpty()) {
first = temp;
} else {
last.next = temp;
}
last = temp;
size++;
}
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item temp = first.data;
if (first == last) {
last = null;
}
first = first.next;
size--;
return temp;
}
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item item = last.data;
size--;
if (first == last) {
first = null;
last = null;
return item;
}
Node temp = first;
while (temp.next != last) {
temp = temp.next;
}
temp.next = null;
last = temp;
return item;
}
public Iterator<Item> iterator() {
return new DequeIterator();
}
public static void main(String[] args) {
String[] items = {"a", "b", "c", "d", "e"};
Deque<String> queue = new Deque<>();
StdOut.println("isEmpty : " + queue.isEmpty() + ", size " + queue.size());
for (String i : items) {
queue.addLast(i);
StdOut.println("isEmpty : " + queue.isEmpty() + ", size " + queue.size());
}
StdOut.println("Iterating");
for (String i : queue) {
StdOut.print(i + " ");
}
StdOut.println("");
while (!queue.isEmpty()) {
StdOut.println("Removing " + queue.removeLast());
StdOut.println("isEmpty : " + queue.isEmpty() + ", size " + queue.size());
}
}
}