-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSafeMutableStack.java
More file actions
61 lines (50 loc) · 1.31 KB
/
SafeMutableStack.java
File metadata and controls
61 lines (50 loc) · 1.31 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
package example4;
import common.BetterMStack;
import common.Optional;
public class SafeMutableStack<T> implements BetterMStack<T> {
protected class Node {
public T value;
public Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
}
protected Node head = null;
protected int length = 0;
public synchronized void push(T value) {
head = new Node(value, head);
length += 1;
}
public synchronized Optional<T> peek() {
if (head != null)
return Optional.of(head.value);
else
return Optional.absent();
}
public synchronized Optional<T> pop() {
if (head != null) {
T result = head.value;
head = head.next;
length -= 1;
return Optional.of(result);
}
else
return Optional.absent();
}
public synchronized void reverse() {
if (head == null) return;
Node prev = null;
Node cursor = head;
while (cursor != null) {
Node next = cursor.next;
cursor.next = prev;
prev = cursor;
cursor = next;
}
head = prev;
}
public synchronized int size() {
return length;
}
}