A stack is a data structure.
An Array follows LIFO(Last In First Out) or FIFO (First In Last Out) order. So, an item inserted first will be the first to remove, if you wish to remove it.
And the definition as on Wikipedia:
In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.
Data structures are so simple if you can understand everything in it. They are just another programs which are tied together with small pieces of implementation.
Push(): To insert an item to the stack.
Pop(): To remove an item off of stack.
To implement we need a pointer to point to the top of the stack, and an object array called data or whatever variable name which will hold the data that is pushed to stack.
Note: The stack that we're implementing here in this blog post is a finite one.
Per the note above, we will have to provide a capacity of the stack(to be a finite stack) during object creation.
The constructor here is just to help with the initial setup to create an array and to set the pointer’s initial position.
Public ArrayStack(int capacity)
data = new obj[capacity];
pointer = 0;
A push operation on stack requires the element to be pushed. Once we add element on to the stack we'll have to increment the pointer to point to the top of the stack.
Public void Push(object o)
data[pointer] = o;
The pop operator doesn't need any input but we'll give the caller what is the element removed now and again the pointer will be decremented to stay on top of the stack.
Public object Pop()
If(IsEmpty()) return null;
object o = data[pointer];
data[pointer] = null;
IsEmpty() used in Pop method is a private method just to check if the array is empty or not. It returns a boolean.
Public bool IsEmpty()
return pointer == 0;
That's it. So simple.
Here is everything to wrap up.