Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ph.edu.dlsu.datsral;
- import java.util.NoSuchElementException;
- public class MyStack<T> {
- private static final int INITIAL_CAPACITY = 4;
- private GenericArray<T> data;
- private int capacity;
- private int count;
- public MyStack() {
- capacity = INITIAL_CAPACITY;
- data = new GenericArray<T>(capacity);
- count = 0;
- }
- public T top() {
- if (empty()) throw new NoSuchElementException("Stack is Empty (Underflow)");
- return data.get(count - 1);
- }
- public void push(T value) {
- if (count == capacity) {
- ensureCapacity();
- }
- data.set(count++, value);
- }
- T pop(){
- if (empty()) throw new NoSuchElementException("Stack is Empty (Underflow)");
- return data.get(--count);
- }
- private void ensureCapacity() {
- System.out.println("Resizing...");
- capacity *= 2;
- GenericArray<T> newArray = new GenericArray<T>(capacity);
- for (int i = 0; i < count; i++) {
- newArray.set(i, data.get(i));
- }
- data = newArray;
- }
- public int size() {
- return count;
- }
- public boolean empty() {
- return count == 0;
- }
- class GenericArray<T> {
- private Object[] data;
- public GenericArray(int n) {
- data = new Object[n];
- }
- public int size() {
- return data.length;
- }
- public T get(int idx) {
- return (T) data[idx];
- }
- public void set(int idx, T item) {
- data[idx] = item;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement