-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayDequeDemo.java
More file actions
179 lines (162 loc) · 6.83 KB
/
Copy pathArrayDequeDemo.java
File metadata and controls
179 lines (162 loc) · 6.83 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package Phase5_CollectionsLambdasStreams.Collections;
import java.util.ArrayDeque;
import java.util.List;
/**
* java.util.ArrayDeque - The Modern Stack-and-Queue Champion
* ----------------------------------------------------------
* ArrayDeque is a RESIZABLE CIRCULAR ARRAY implementation of Deque. It can
* be used as either a QUEUE, a STACK, or a true DEQUE. In most cases it is
* the right answer:
* <p>
*
* Stack prefer ArrayDeque over java.util.Stack
* Queue prefer ArrayDeque over LinkedList
* Deque prefer ArrayDeque over LinkedList
* <p>
*
* Why It Exists
* -------------
* - java.util.Stack extends Vector, which is synchronized and slow.
* - LinkedList works but is heavy: each node is a separate object, two
* pointers, and worse cache locality.
* - ArrayDeque packs elements in one contiguous array - smaller memory,
* better cache behaviour, no synchronisation tax.
* <p>
*
* Constructors
* ------------
* new ArrayDeque<>() capacity 16
* new ArrayDeque<>(int numElements) initial capacity
* new ArrayDeque<>(Collection) copy of another collection
* <p>
*
* Methods - Three Faces of the Same Object
* ----------------------------------------
* <p>
*
* FIFO (Queue) LIFO (Stack) Deque (both ends)
* ---------------------- -------------------- --------------------
* offer/offerLast (e) push (e) addFirst/addLast (e)
* poll/pollFirst () pop () pollFirst/pollLast ()
* peek/peekFirst () peek () peekFirst/peekLast ()
* <p>
*
* Throw-on-failure variants:
* add(e)/addLast(e)/addFirst(e)
* remove() / removeFirst() / removeLast()
* element() / getFirst() / getLast()
* <p>
*
* Restrictions
* ------------
* - NULL elements are NOT allowed (intentional - null is reserved as the
* "queue is empty" sentinel for poll/peek). Use LinkedList if you need
* to store nulls (rare).
* - NOT thread-safe. For concurrent access use a ConcurrentLinkedDeque or
* a BlockingDeque.
* <p>
*
* Big-O
* -----
* add / remove / peek at either end O(1) amortised
* contains / remove(Object) O(n)
* <p>
*
* Iteration
* ---------
* iterator() first-to-last
* descendingIterator() last-to-first
*/
public class ArrayDequeDemo {
public static void main(String[] args) {
section("1) FIFO queue usage");
ArrayDeque<String> q = new ArrayDeque<>();
q.offer("first");
q.offer("second");
q.offer("third");
System.out.println("queue = " + q);
System.out.println("peek = " + q.peek());
System.out.println("poll = " + q.poll() + " -> " + q);
section("2) LIFO stack usage");
ArrayDeque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("stack (top first) = " + stack);
System.out.println("peek = " + stack.peek());
System.out.println("pop = " + stack.pop() + " -> " + stack);
section("3) Deque - work at BOTH ends");
ArrayDeque<Integer> d = new ArrayDeque<>();
d.addFirst(2);
d.addFirst(1);
d.addLast(3);
d.addLast(4);
System.out.println("deque = " + d);
System.out.println("peekFirst = " + d.peekFirst());
System.out.println("peekLast = " + d.peekLast());
System.out.println("removeFirst -> " + d.removeFirst() + " deque=" + d);
System.out.println("removeLast -> " + d.removeLast() + " deque=" + d);
section("4) Throws vs returns-special");
ArrayDeque<Integer> e = new ArrayDeque<>();
System.out.println("pollFirst on empty = " + e.pollFirst()); // null
System.out.println("peekFirst on empty = " + e.peekFirst()); // null
try { e.getFirst(); }
catch (java.util.NoSuchElementException ex) {
System.out.println("getFirst on empty -> NoSuchElementException");
}
section("5) null rejection - deliberate safety");
try { new ArrayDeque<>().offer(null); }
catch (NullPointerException ex) {
System.out.println("offer(null) -> NullPointerException");
}
section("6) Iteration direction");
ArrayDeque<Integer> walk = new ArrayDeque<>(List.of(1, 2, 3, 4, 5));
System.out.print("forward : "); walk.forEach(n -> System.out.print(n + " "));
System.out.println();
System.out.print("backward: ");
for (java.util.Iterator<Integer> it = walk.descendingIterator(); it.hasNext(); ) {
System.out.print(it.next() + " ");
}
System.out.println();
section("7) Reverse a string using a stack");
String text = "hello";
ArrayDeque<Character> chars = new ArrayDeque<>();
for (char c : text.toCharArray()) chars.push(c);
StringBuilder reversed = new StringBuilder();
while (!chars.isEmpty()) reversed.append(chars.pop());
System.out.println("reverse(\"" + text + "\") = " + reversed);
section("8) Sliding-window maximum (classic deque problem)");
int[] arr = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
ArrayDeque<Integer> idx = new ArrayDeque<>(); // holds INDICES
StringBuilder maxes = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
// drop indices that fell out of the window
while (!idx.isEmpty() && idx.peekFirst() <= i - k) idx.pollFirst();
// maintain a decreasing deque
while (!idx.isEmpty() && arr[idx.peekLast()] <= arr[i]) idx.pollLast();
idx.offerLast(i);
if (i >= k - 1) maxes.append(arr[idx.peekFirst()]).append(' ');
}
System.out.println("input = " + java.util.Arrays.toString(arr));
System.out.println("max of every " + k + " = " + maxes.toString().trim());
section("9) Performance teaser - ArrayDeque vs LinkedList");
final int N = 1_000_000;
long t = System.nanoTime();
ArrayDeque<Integer> a = new ArrayDeque<>();
for (int i = 0; i < N; i++) a.push(i);
while (!a.isEmpty()) a.pop();
long aMs = (System.nanoTime() - t) / 1_000_000;
t = System.nanoTime();
java.util.LinkedList<Integer> l = new java.util.LinkedList<>();
for (int i = 0; i < N; i++) l.push(i);
while (!l.isEmpty()) l.pop();
long lMs = (System.nanoTime() - t) / 1_000_000;
System.out.println("ArrayDeque push+pop x " + N + ": " + aMs + " ms");
System.out.println("LinkedList push+pop x " + N + ": " + lMs + " ms");
// OUTPUT (timings vary)
}
private static void section(String title) {
System.out.println("\n====== " + title + " ======");
}
}