-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayStack.java
More file actions
56 lines (47 loc) · 1.61 KB
/
ArrayStack.java
File metadata and controls
56 lines (47 loc) · 1.61 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
import java.util.*;
public class ArrayStack < E > {
public static final int CAPACITY = 1000;
private int topIndex;
private E[] data;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int capacity) {
topIndex = -1;
data = (E[]) new Object[capacity];
}
public int size() {
return (topIndex + 1);
}
public boolean empty() {
return (topIndex == -1);
}
public void push(E e) throws IllegalStateException {
if (size() == data.length) throw new IllegalStateException("Stack is full");
data[++topIndex] = e;
}
public E peek() throws EmptyStackException {
if (empty()) throw new EmptyStackException();
return data[topIndex];
}
public E pop() throws EmptyStackException {
if (empty()) throw new EmptyStackException();
E answer = data[topIndex];
data[topIndex] = null;
topIndex--;
return answer;
}
public static void main(String args[]) {
ArrayStack < Integer > mystack = new ArrayStack<>();
mystack.push(9);
mystack.push(3);
mystack.push(8);
System.out.println("Element at the top is :" + mystack.peek());
System.out.println("Element removed is : " + mystack.pop());
System.out.println("The size of the stack is : " + mystack.size());
System.out.println("Element removed is : " + mystack.pop());
System.out.println("Element at the top is : " + mystack.peek());
mystack.push(10);
System.out.println("Stack is empty : " + mystack.empty());
}
}