Growing Stack - Java Data Structure

Java examples for Data Structure:Stack

Description

Growing Stack

Demo Code

package com.company.stucts.stack;

import java.util.Arrays;

public class GrowingStack {
    private Object[] data;
    private int top;

    public GrowingStack(int size) {
        if (size < 0) {
            throw new IllegalStateException("Stack size negative value!");
        }/*from ww  w.j  a va 2 s  .co  m*/
        data = new Object[size];
        top = 0;
    }

    public void push(Object o) {
        ensureCapacity();
        data[top++] = o;
    }

    public Object pop() {
        if (top == 0) {
            throw new IllegalStateException("Stack is empty");
        }
        Object o = data[--top];
        data[top] = null;
        return o;
    }

    public boolean isEmpty() {
        return top != 0;
    }

    private void ensureCapacity() {
        if (top == data.length) {
            int oldSize = data.length;
            int newSize = oldSize * 2 + 1;
            System.out.println("Stack is grow! Old size: " + oldSize
                    + ", new size: " + newSize);
            data = Arrays.copyOf(data, newSize);
        }
    }

    @Override
    public String toString() {
        return "Queue: " + "\n" + "data[]: " + Arrays.toString(data) + "\n"
                + "data[] length: " + data.length + "\n" + "top: " + top;
    }

    public static void main(String[] args) {
        GrowingStack stack = new GrowingStack(0);
        stack.push("Hello");
        stack.push("World");

        while (stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }
}

Related Tutorials