Friday, November 27, 2015

Stack implementation using Array

public class Stack {
    int[] array;
    private int top;
    private int size;
    public Stack(int size) {
        this.size=size;
        array = new int[size];
        top = -1;
    }
    public void push (int... data)    {
        int size = data.length;
        for(int i=0; i<size; i++)
            push(data[i]);
    }
    public void push (int data)    {
        if (top<size-1)    {
            top++;
            array[top]=data;
        }
    }
    public final static int ErrorCode = -999;
    public int pop()    {
        if(!isEmpty())    {
            int a = array[top];
            top--;
            return a;
        }    else return ErrorCode;
    }
    public int peek()    {
        return array[top];
    }
    public boolean isEmpty()    {
        if(top<0) return true;
        else    return false;
    }
    public void printArray()    {
        int size = top+1;
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<size; i++)
            sb.append(array[i]).append(", ");
        System.out.println(sb.toString());   
    }
}

No comments:

Post a Comment

UA-39217154-2