-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStack.java
More file actions
55 lines (46 loc) · 1.11 KB
/
Copy pathStack.java
File metadata and controls
55 lines (46 loc) · 1.11 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
public class Stack<E>{
private E[] elements;
private int top;
@SuppressWarnings("unchecked")
Stack(int size){
if(size < 2){
throw new IllegalArgumentException(" " + size);
}
elements = (E[])new Object[size];
top = -1;
}
void push (E element) throws StackFullException{
if (top == elements.length - 1){
throw new StackFullException();
}
elements[++top] = element;
}
E pop() throws StackEmptyException{
if(isEmpty()){
throw new StackEmptyException();
}
return elements[top--];
}
boolean isEmpty(){
return top == -1;
}
public static void main(String[] args) throws StackFullException, StackEmptyException{
Stack<String> stack = new Stack<String>(5);
assert stack.isEmpty();
stack.push("A");
stack.push("B");
stack.push("C");
stack.push("D");
stack.push("E");
// Simulate a exception occurance
//stack.push("F");
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
// Simulate to cause a StackEmptyException.
stack.pop();
assert stack.isEmpty();
}
}
class StackEmptyException extends Exception{}
class StackFullException extends Exception{}