C # Stack Source profiling

Source: Internet
Author: User

Source code version for. NET Framework 4.6.1

Keep up to date on this series

There are inputs and outputs.

(Note: Non-basic, mainly related to the implementation principle of the stack)

The level is limited, if there is something wrong, look at it.

A stack represents a last-in-first-out (LIFO) collection of objects. Implements the ICollection interface.

Concept
Definition: A linear table that restricts insertion or deletion only at the end of a table, the footer corresponds to the top of the stack, the table header corresponds to the bottom of the stack, and the stack without elements is called an empty stack.
Into the stack: insert an element into the top of the stack.
Stack: Delete an element at the top of the stack

Element operations can only be done at the top of the stack, the last element into the stack is the first stack, the structure of the diagram is as follows:

Go to Theme

Basic members

        private T[] _array;     // 用于存储栈元素的数组        privateint _size;           // 栈元素的数量        privateconstint4// 默认初始容量        staticnew T[0];  // 空数组,用于赋默认值

constructor function

The stack has three constructors, respectively:

(1) Use the default value of stack set, not recommended (because dynamic expansion requires additional computation and open up new memory space, dynamic expansion should occur in the case of exceeding the expected capacity value, suppress overflow);

        publicStack() {            _array = _emptyArray;            0;            0;        }

(2) using a non-negative integer to set an initial capacity of the stack, it is recommended (given an expected capacity value, if the expected value is small, will automatically expand, and do not worry about overflow)

        publicStack(int capacity) {            if0)                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNumRequired);            new T[capacity];            0;            0;        }

(3) Populating with an existing non-null reference collection initializes the Stack,stack with the same length as the collection and, in the order in which the collection elements are stored (it is recommended to achieve some performance gains by implementing a collection of collection generic interfaces).

         Public Stack(Ienumerable<t> Collection) {if(collection==NULL) throwhelper.throwargumentnullexception (exceptionargument.collection); icollection<t> C = Collection asicollection<t>;if(c! =NULL) {//Implements a collection of ICollection generic interfaces, simple brute, allocation space, array duplication                intCount = C.count; _array =NewT[count]; C.copyto (_array,0);            _size = count; }Else{_size =0;//Do not implement ICollection generic interface, default initial capacity is 4, space is not enough also need dynamic expansion_array =NewT[_defaultcapacity];//Traverse element to perform a stack operation                using(Ienumerator<t> en = collection. GetEnumerator ()) { while(En. MoveNext ()) {Push (en.                                                        Current); }                }            }        }

Into the stack

The stack is one of the core methods of the stack, inserting elements from the top of the stack into the stack. Conditions that trigger dynamic expansion when and only if the number of elements equals the length of an array of internal storage elements, a new memory space is opened up, twice times the original memory space will be reclaimed by GC and freed up resources

        publicvoidPush(T item) {            //动态扩容            if (_size == _array.Length) {                new02*_array.Length];                00, _size);                _array = newArray;            }            //将元素存于栈顶位置            _array[_size++] = item;            _version++;        }

Out of the stack

The stack is one of the core methods of stack, get the element at the top of the stack, the empty stack does not have the stack function (forcing use will throw an exception). are divided into two types:
(1) only the top element of the stack is fetched, not removed.

        publicPeek() {            if (_size==0)                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);            return _array[_size-1];//获取栈顶元素        }

(2) Gets the top element of the stack and removes it.

        publicPop() {            if0)                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);            _version++;            T item = _array[--_size];       // 获取栈顶元素,同时栈顶指针前移一位            default(T);     // 释放栈顶的内存空间            return item;        }

Space Compression
If the actual number of elements is less than 90% of the current capacity, set the capacity to the actual number of elements in the stack. It is recommended that you make sure that there are no more elements in the stack and that the initialization capacity is much larger than the expected value.

        publicvoidTrimExcess() {            int threshold = (int)(((double0.9);                         if( _size < threshold ) {                new T[_size];                00, _size);                    _array = newarray;                _version++;            }        }    

Traverse
The stack implements the GetEnumerator () of the IEnumerable generic interface and returns a struct:

      Public structEnumerator:ienumerator<t>, system.collections.ienumerator{PrivateStack<t> _stack;//Traversal of the current stack            Private int_index;//Traverse identity            Private int_version;PrivateT currentelement;//Current stack element            //Initialize Method            Internal Enumerator(stack<t> Stack)                {_stack = stack;                _version = _stack._version; _index =-2; Currentelement =default(T); }//Pointer movement, traversing the required method             Public BOOL MoveNext() {BOOLretvalif(_version! = _stack._version) Throwhelper.throwinvalidoperationexception (exceptionresource.invalidoperation_enumfailedversion);if(_index = =-2) {//Start traversal_index = _stack._size-1; retval = (_index >=0);if(retval) currentelement = _stack._array[_index];returnretval }if(_index = =-1) {//END Traversal                    return false; } retval = (--_index >=0);if(retval) currentelement = _stack._array[_index];ElseCurrentelement =default(T);returnretval }//Gets the current element of the traversal, used in conjunction with MoveNext, which iterates through the required properties             PublicT Current {Get{if(_index = =-2) throwhelper.throwinvalidoperationexception (exceptionresource.invalidoperation_enumnotstarted);if(_index = =-1) throwhelper.throwinvalidoperationexception (exceptionresource.invalidoperation_enumended);returnCurrentelement; }            }        }

C # Stack Source profiling

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.