-
Notifications
You must be signed in to change notification settings - Fork 28
/
SStack.java
74 lines (53 loc) · 1.06 KB
/
SStack.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
package ds_010_trees;
public class SStack<T> {
private final Node<T> TOP;
private int size;
public SStack(){
TOP = new Node<>(null, null);
size = 0;
}
public void push(T value) {
Node<T> newNode = new Node<>(value, TOP.next);
TOP.next = newNode;
size++;
}
public T pop() {
if(isEmpty()) {
return null;
}
T val = TOP.next.value;
TOP.next = TOP.next.next;
size--;
return val;
}
// trivial methods
public void print() {
System.out.print("STACK: ");
if(size == 0) {
System.out.print("EMPTY\n");
return;
}
for(Node<T> node = TOP.next; node != null; node = node.next) {
System.out.printf("%s ", node.value);
}
System.out.print("\n");
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
// inner class
private static class Node<T> {
public final T value;
public Node<T> next;
public Node(final T value) {
this.value = value;
}
public Node(final T value, final Node<T> next) {
this.value = value;
this.next = next;
}
}
}