-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackAsList.java
More file actions
99 lines (83 loc) · 2.09 KB
/
Copy pathStackAsList.java
File metadata and controls
99 lines (83 loc) · 2.09 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public class StackAsList implements Stack {
private Node top;
@Override
public boolean isEmpty() {
if(top != null) {
return false;
} else {
return true;
}
}
@Override
public String toString()
{
String s = "";
Node current = top;
while(current != null)
{
if(s.isEmpty()) {
s = "" + current.getData();
current = current.next;
} else {
s = s + "; " + current.getData();
current = current.next;
}
}
return s;
}
@Override
public Object peek() {
try { // catches an exception for when
return top.getData(); // there is the request to peek
} catch (Exception e) { // but the Stack is empty
return "Error: The Stack is empty!";
}
}
@Override
public void push(Object elem) {
try {
Node newNode = new Node(elem); // We don't really need this try-catch
newNode.next = top; // as the linked List could grow
top = newNode; // endlessly so the exception will
} catch (Exception e) { // never be thrown
System.out.println("Error: The Stack is full");
}
}
@Override
public Object pop() {
try { // catches an exception for when
Node newNode = top; // there is the request to pop
top = top.next; // but the Stack is empty
return newNode.getData();
} catch (Exception e) {
return "Error: The Stack is empty!";
}
}
private class Node {
public Object data;
public Node next;
Node(Object data) {
this.data = data;
}
public Object getData() {
return data;
}
}
public static void main(String[] args) {
StackAsList stack = new StackAsList(); // we tested the console output by calling
// the methods and triggering an exception
String s = "Hello"; // in the end.
String t = "Good";
String u = "Morning";
System.out.println(stack.isEmpty());
stack.push(s);
stack.push(t);
stack.push(u);
System.out.println(stack.isEmpty());
System.out.println(stack.toString());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}