// Empty stack condition: this. _ size =-1
// Full stack condition: this. Count = this. _ array. Length
// Change it by yourself. this. _ size points directly to the top element of the stack.
Using System;
Namespace Stack
{
Class Stack2
{
// Member
Private object [] _ array; // array of Elements
Private const int _ defacapcapacity = 10; // default Space
Private int _ size; // point to the top element of the stack
// Attributes
Public virtual int Count // number of elements
{
Get
{
Return (this. _ size + 1 );
}
}
// Constructor
Public Stack2 ()
{
This. _ array = new object [_ defacapcapacity];
This. _ size =-1;
}
Public Stack2 (int initialCapacity)
{
If (initialCapacity <0)
{
Throw new ArgumentOutOfRangeException ("stack space cannot be less than zero ");
}
If (initialCapacity <_ defaultCapacity)
{
InitialCapacity = _ defaultCapacity;
}
This. _ array = new object [initialCapacity]; // allocate stack space
This. _ size =-1;
}
// Method
Public virtual object Pop () // output Stack
{
If (this. _ size =-1)
{
Throw new ArgumentOutOfRangeException ("stack overflow ");
}
Object obj2 = this. _ array [this. _ size]; // gets the top element of the stack.
This. _ array [this. _ size --] = null; // deletes the top element of the stack.
Return obj2;
}
Public virtual void Push (object obj) // stack entry
{
If (this. Count = this. _ array. Length)
{
Object [] destinationArray = new object [2 * this. _ array. Length]; // if the space is full, the expansion is twice the original size.
Array. Copy (this. _ array, 0, destinationArray, 0, this. Count );
This. _ array = destinationArray;
}
This. _ array [++ this. _ size] = obj; // stack entry
}
}
}