-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayImplementation.java
More file actions
92 lines (76 loc) · 2.15 KB
/
ArrayImplementation.java
File metadata and controls
92 lines (76 loc) · 2.15 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package Stacks;
import java.lang.reflect.Array;
import java.util.EmptyStackException;
/**
* Adv : size or space taken is less / display is better.
* DisAdv : fixed size / overflow
*/
public class ArrayImplementation {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>(Integer.class);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.peek());
System.out.println(stack.size());
System.out.println(stack.isEmpty());
}
public static class Stack<T> {
private final T[] arr;
private int currentIndex;
/**
* Creates stack of default size 5.
*/
@SuppressWarnings("unchecked")
Stack(Class<T> clazz) {
arr = (T[]) Array.newInstance(clazz, 5);
currentIndex = 0;
}
@SuppressWarnings("unchecked")
Stack(Class<T> clazz, int size) {
arr = (T[]) Array.newInstance(clazz, size);
currentIndex = 0;
}
void push(T x) {
if (isFull()) {
throw new IndexOutOfBoundsException("Stack is Full");
}
arr[currentIndex] = x;
currentIndex++;
}
T peek() {
if (currentIndex == 0) {
throw new EmptyStackException();
}
return arr[currentIndex - 1];
}
T pop() {
if (currentIndex == 0) {
throw new EmptyStackException();
}
T top = arr[currentIndex - 1];
currentIndex--;
return top;
}
void display() {
for (T num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
int size() {
return currentIndex;
}
boolean isEmpty() {
return currentIndex == 0;
}
boolean isFull() {
return currentIndex == arr.length;
}
int capacity() {
return arr.length;
}
}
}