-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArrayStack.java
63 lines (54 loc) · 1.4 KB
/
ArrayStack.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
import java.util.EmptyStackException;
/**
* Implementation of a Last In First Out data structure
* @param <E>
*/
abstract class ArrayStack<E> implements Stack<E> {
public E[] stackarray;
private int top;
//constructor
public ArrayStack(int initsize){
stackarray = (E[]) new Object[initsize];
top = -1;
}
//adds an item in the stack
public E push(E o){
return stackarray[++top] = o;
}
//returns the item on top of the stack
public E top() throws EmptyStackException{
if(top==-1){
throw new EmptyStackException();
}else{
return stackarray[top];
}
}
//removes the last item
public E pop() throws EmptyStackException{
if(top==-1){
throw new EmptyStackException();
}
return stackarray[top--];
}
//removes a given number of items
public void popMany(int x){
for(int i = 0; i < x; i++){
pop();
}
}
//checks if the stack is empty
public boolean isEmpty(){
return top == -1;
}
//returns the size of the stack
public int size(){
return top+1;
}
//displays the stack
public void display() {
for(int i=0;i<=top;i++){
System.out.print(stackarray[i]+ " ");
}
System.out.println();
}
}