-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStack.java
More file actions
79 lines (61 loc) · 1.37 KB
/
Copy pathStack.java
File metadata and controls
79 lines (61 loc) · 1.37 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
import java.lang.Exception;
public class Stack implements Coll{
private class Node {
private Node next;
private int data;
public Node(int data) {
this.data = data;
this.next = null;
}
public Node() {
this(-1);
}
public int getData() {
return(this.data);
}
public void setData(int data) {
this.data = data;
}
public void setNext(Node node) {
this.next = node;
}
public Node getNext() {
return(this.next);
}
}
private Node start;
public Stack() {
start = new Node();
}
public void add(int data) {
Node n = new Node(data);
n.setNext(start.getNext());
start.setNext(n);
}
public int remove() throws Exception {
if (start.getNext() == null) {
throw new Exception("Cannot remove from empty list");
}
int tmp = this.start.getNext().getData();
start.setNext(start.getNext().getNext());
return(tmp);
}
public boolean isEmpty() {
return(start.getNext() == null);
}
public static void main(String[] args) {
Stack ll = new Stack();
// ArrayList<Integer> ll = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
ll.add(i * 2);
}
try {
while (!ll.isEmpty()) {
System.out.println(ll.remove());
}
} catch (Exception e) {
System.out.println("Attempted to remove from empty stack");
System.exit(-1);
}
}
}