Reference from: [Michael McMillan. Data Structures and Algorithms Using C #]
The implementation here is to use ArrayList. When a new data item is added to the stack, you do not need to worry about adjusting the table size. I think this implementation is clear, where p_index points directly to the top element of the stack.
Using System;
Using System. Collections;
Namespace Stack
{
Class CStack
{
Private int p_index; // stack top
Private ArrayList list;
// Attributes
Public int Count
{
Get {return list. Count ;}
}
// Constructor
Public CStack ()
{
List = new ArrayList ();
P_index =-1;
}
Public void Push (object item) // stack entry
{
List. Add (item );
P_index ++;
}
Public object Pop () // output Stack
{
Object obj = list [p_index];
List. RemoveAt (p_index );
P_index --;
Return obj;
}
Public void Clear () // Clear the stack
{
List. Clear ();
P_index =-1;
}
Public object Peek () // returns the top element of the stack.
{
Return list [p_index];
}
}
}