Stack sequential storage structure _ C # Implementation 3 [array implementation]

Source: Internet
Author: User

// 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

}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.