Data Structures

Home   Index

Stack

A stack is an abstract data type that functions with a last in, first out policy.
Create an array of fixed length. Set a variable to -1 indicating the top of the stack. You can then create these methods:

Java example of a stack

import java.lang.String;
import java.lang.Boolean;

public class Stack
{
    private String[] _array;
    private int _max;
    private int _top = -1;
    
    public Stack()
    {
        _array = new String[10];
        _max = 10;
    }
    
    public Stack(int size)
    {
        _array = new String[size];
        _max = size;
    }
    
    public Boolean Push(String element)
    {
        if (this.Size() < this._max)
        {
            this._top++;
            this._array[this._top] = element;
            return true;
        }
        return false;
    }
    
    public String Pop()
    {
        if (!this.IsEmpty())
        {
            this._top--;
            return this._array[this._top + 1];
        }
        return "";
    }
    
    public int Size()
    {
        return this._top + 1;
    }
    
    public Boolean IsEmpty()
    {
        if (this._top == -1) return true;
        return false;
    }
    
    public String Peek()
    {
        if (!this.IsEmpty()) return this._array[this._top];
        return null;
    }
    
    public String ToString()
    {
        String elements = "The elements in this stack are [";
        for (int i = 0; i < this.Size(); i++)
        {
            if (i != 0) elements += ", ";
            elements += this._array[i];
        }
        elements += "]";
        return elements;
    }
}
Next