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:
Adds an element to the top of the stack.
Returns and removes the top element from the stack.
Returns the size of the stack.
Returns true if the stack is empty, otherwise false.
Returns the top element from the stack without removing it.
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;
}
}