-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayBasedStack.java
73 lines (56 loc) · 1.29 KB
/
ArrayBasedStack.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
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
public class ArrayBasedStack<T> implements StackInterface<T> {
private int top;
private T [] stack;
private int size;
public ArrayBasedStack() {
top = -1;
size = 0;
stack = (T[]) new Object[100];
}
public ArrayBasedStack(int sizeOfStack) {
top = -1;
size = 0;
stack = (T[])new Object[sizeOfStack];
}
@Override
public void push(T item) throws StackFullException {
// TODO Auto-generated method stub
if(top < stack.length-1) {
top++;
size++;
stack[top] = item;
}
else
throw new StackFullException("Push attempted on a full stack! No more can be added");
}
@Override
public void pop() throws StackEmptyException {
// TODO Auto-generated method stub
if(top > -1) {
stack[top] = null;
top--;
size--;
}
else throw new StackEmptyException("Pop attempted on a empty stack!");
}
@Override
public T top() throws StackEmptyException {
// TODO Auto-generated method stub
if(top > -1)
return stack[top];
else
throw new StackEmptyException("Top attempted on an empty stack");
}
public String toString() {
String allItems = "";
for(int i = top; i > -1; i--) {
allItems = allItems + " \n" + stack[i].toString();
}
return allItems;
}
@Override
public int size() {
// TODO Auto-generated method stub
return size;
}
}