-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathStackExample.java
67 lines (51 loc) · 1.59 KB
/
StackExample.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
package Java;
import java.util.Arrays;
public class StackExample {
static class Stack {
private Element last;
private int count;
public void push(final String value) {
last = new Element(last, value);
count++;
}
public String pop() {
if (count == 0) {
throw new NullPointerException("Stack is empty");
}
final Element result = last;
last = last.prev;
count--;
return result.value;
}
public String[] asArray() {
final String[] result = new String[count];
Element current = last;
for (int i = count - 1; i >= 0; i--) {
result[i] = current.value;
current = current.prev;
}
return result;
}
private static class Element {
private final Element prev;
private final String value;
public Element(final Element prev, final String value) {
this.prev = prev;
this.value = value;
}
}
}
// Usage
public static void main(final String[] args) {
final Stack stack = new Stack();
stack.push("first");
stack.push("second");
stack.push("third");
String[] array = stack.asArray();
System.out.println(Arrays.toString(array));
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
//System.out.println(stack.pop());
}
}