Reference: [Chen guang. Data Structure (C # language description)]
Stack null condition: this. _ size = 0
Full stack condition: this. _ size = this. _ array. Length
The top pointer of a non-empty stack is always at the next position of the top element of the stack.
Using System;
Namespace Stack
{
Class Stack
{
// Member
Private object [] _ array; // array of Elements
Private const int _ defacapcapacity = 10; // default Space
Private int _ size; // indicates the number of elements.
// Attributes
Public virtual int Count // number of elements
{
Get
{
Return this. _ size;
}
}
// Constructor
Public Stack ()
{
This. _ array = new object [_ defacapcapacity];
This. _ size = 0;
}
Public Stack (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 = 0;
}
// Method
Public virtual object Pop () // output Stack
{
If (this. _ size = 0)
{
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. _ size = 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. _ size );
This. _ array = destinationArray;
}
This. _ array [this. _ size ++] = obj; // stack entry
}
}
}