-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyStack.java
48 lines (41 loc) · 1.17 KB
/
MyStack.java
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
import java.util.ArrayList;
public class MyStack<E> implements StackInterface<E>{
ArrayList<E> array = new ArrayList<>();
public static final int MAX_SIZE = 15; //Arbitrary value since ArrayList has a very large cap. Changeable.
private int top = -1;
public void push(E j) throws StackFullException{
if (isFull()){
throw new StackFullException("Stack is already full!");
}
else {
array.add(j);
top++;
}
}
public void pop() throws StackEmptyException{
if (isEmpty()){
throw new StackEmptyException("Stack is empty!");
}
else {
array.remove(top);
top--;
}
}
public E top() throws StackEmptyException{
if (isEmpty()){
throw new StackEmptyException("Stack is empty!");
}
else {
return array.get(top);
}
}
public boolean isEmpty(){
return top == -1; //returns true if top == -1
}
public boolean isFull(){
return top == MAX_SIZE;
}
public int size(){
return array.size();
}
}