-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericStack.java
More file actions
53 lines (44 loc) · 1.25 KB
/
GenericStack.java
File metadata and controls
53 lines (44 loc) · 1.25 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
public class GenericStack<T> {
private Node first;
private class Node {
private T item;
private Node next;
}
public boolean isEmpty() {
return first == null;
}
public void push(T item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
}
public T pop() {
T item = first.item;
first = first.next;
return item;
}
public static void main(String[] args) {
GenericStack<Integer> ints = new GenericStack<>();
ints.push(1);
ints.push(2);
ints.push(3);
while(!ints.isEmpty()) {
System.out.println(ints.pop());
}
GenericStack<String> strings = new GenericStack<>();
strings.push("1");
strings.push("hello");
strings.push("world");
while(!strings.isEmpty()) {
System.out.println(strings.pop());
}
GenericStack<Animal> animals = new GenericStack<>();
animals.push(new Cat("Brown", "Roadhouse"));
animals.push(new Cat("Black", "Bub"));
animals.push(new Cat("Gray", "Pickles"));
while(!animals.isEmpty()) {
System.out.println(animals.pop());
}
}
}