-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArrayStack.java
More file actions
35 lines (27 loc) · 845 Bytes
/
ArrayStack.java
File metadata and controls
35 lines (27 loc) · 845 Bytes
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
package com.ub.interview;
public class ArrayStack<E> {
private static final int INTIAL_CAPACITY = 10;
private E[] stack;
private int currentSize = 0;
private int currentCapacity = 0;
public ArrayStack() {
currentCapacity = INTIAL_CAPACITY;
stack = (E[]) new Object[currentCapacity];
}
public void push(E element){
verifyCapacity();
stack[currentSize++] = element;
}
public E pop() {
return stack[--currentSize];
}
private void verifyCapacity() {
if( currentSize == currentCapacity) {
//Reallocate data to stack as stack is reference variable
currentCapacity = 2*currentCapacity;
E[] newStack = (E[]) new Object[currentCapacity];
System.arraycopy(stack, 0, newStack, 0, currentSize);
stack = newStack; //Update the reference for stack to newStack
}
}
}