-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTheStack.java
More file actions
70 lines (60 loc) · 1.25 KB
/
TheStack.java
File metadata and controls
70 lines (60 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class TheStack<T> {
private Node top;
private int size = 0;
private class Node {
T data;
Node next;
public Node(T val) {
this.data = val;
this.next = null;
}
}
public void push(T val) {
Node temp = new Node(val);
temp.next = top;
top = temp;
this.size ++;
}
public T pop() throws StackEmptyException {
if(isEmpty()) {
String msg = "The stack is empty, there is nothing to pop.";
throw new StackEmptyException(msg);
}
T data = top.data;
top = top.next;
this.size --;
return data;
}
public T peek() throws StackEmptyException {
if (!isEmpty()) {
return top.data;
}
else {
String msg = "The stack is empty, there is nothing to peek at.";
throw new StackEmptyException(msg);
}
}
public void display() throws StackEmptyException{
if (isEmpty()) {
String msg = "The stack is empty, there is nothing to display.";
throw new StackEmptyException(msg);
}
else {
Node temp = top;
System.out.print("(top) ");
while (temp != null) {
System.out.print(temp.data);
temp = temp.next;
if(temp != null)
System.out.print("->");
}
System.out.println(" (bottom)");
}
}
public boolean isEmpty() {
return top == null;
}
public int getSize() {
return size;
}
}