Stack Implementation


The stack is linear data structure, in which the first added element should be taken last from the stack. In this manner, the stack obeys to the Last-in-last-out (LIFO) policy. Theoretically, the stack can store any kind of abstract data types as elements, but there are two basic operations – push and pop.

The push operation adds an element to the top of the stack. That way, the access to the lower elements is removed and the stack could be initialized if it is empty.

The pop operation retrieves and removes the first element from the top of the stack. This is element is returned by this operation. That way, elements from under levels could be accessed or to come to an empty stack.

The nature of the push and pop operations adds to the elements of the stack natural order. The elements are removed in reverse order of their addition (pushing) to the stack. That is why the lower elements are those that are for longer time staying at the stack.

Here is my implementation of queue:

/**
 * Stack implementation
 * @author Hristo Georgiev
 */

public class xStack<T> {
    private final int INITIAL_ARRAY_LENGTH = 4;
    private int size;
    private int count;
    private T[] stack;

    /**
    * Constructor of empty stack
    */

    public xStack(){
        this.count = -1;
        this.size = INITIAL_ARRAY_LENGTH;
        this.stack = (T[])new Object[this.size];
    }

    /**
    * Push an element in the head of the stack
    */

    public void push(T element){
        this.count++;
        if(this.count >= this.size){
            this.resizeArray();
        }
        stack[this.count] = element;
    }

    /**
    * Pop an element from the head of the stack
    */

    public T pop(){
        if(!isEmpty()){
            return this.stack[this.count];
        }else{
            return null;
        }
    }

    /**
    * Checks if the stack is empty
    */

    public boolean isEmpty(){
        if(this.count == 0){
            return true;
        }
        return false;
    }

    private void resizeArray(){
        T[] newStack = (T[])new Object[2*this.size];
        System.arraycopy(this.stack, 0, newStack, 0, this.size);
        this.stack = newStack;
        this.size *= 2;
    }
}