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

Source: Internet
Author: User

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

}

}
}

 

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.