Stack<T> Methods in C#
DevSniper
173 Views
Methods
- Push(T) :- public void Push (T item);It will insert an element at the top of the Stack<T>. It is O(1) Operation
- Pop :- public T Pop ();It will remove top element of the stack and return that element. it will throw InvalidOperationException if stack is empty. Time Complexity is O(1)
- Peek :- public T Peek ();It will return top element of the Stack<T> without removing that. It is a O(1) Operation. and will throw InvalidOperationException if stack is Empty
- Clear :- public void Clear ();It will remove all elements from the Stack<T>. It is an O(n) operation
- Contains(T) :- public bool Contains (T item);Returns true if element is present in the Stack<T> otherwise false. It is an O(n) operation.
- CopyTo(T,int) :- public void CopyTo (T[] array, int arrayIndex);Copy Stack<T> elements into provided 1-D array from index, arrayIndex passed by params (zero-based index) . It is an O(n) operation.
- EnsureCapacity (int ) :- public int EnsureCapacity (int capacity);If the current capacity is less than provided capacity. it is increased Stack<T> capacity to at least the specified capacity.
- Equals(Object) :- public virtual bool Equals (object? obj);Returns true if specified object is equals to the current object.
- GetEnumerator :- public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator ();it will return an enumerator of the Stack<T>. it is an O(1) operation.
- GetHashCode :- public virtual int GetHashCode ();Returns a hash code of current object.
- GetType :- public Type GetType ();Returns the type of current instance.
- MemberwiseClone :- protected object MemberwiseClone ();it will creates and return a shallow copy of the current Object.
- ToArray :- public T[] ToArray ();It will create a new array and copy all elements of Stack<T> into that array and return that array.
- ToString :- public virtual string? ToString ();It will return a string that represents the current object.
- TrimExcess:- public void TrimExcess ();if that number is less than 90 % of current capacity then it will sets the capacity to the actual number of elements in the Stack<T>. It is an O(n) operation.
- TryPeek(T) :- public bool TryPeek (out T result);It will return true if top element exist otherwise false ( if stack is empty). in out param, if top element present, set top element of the Stack<T> without removing that from stack otherwise for empty case, set default value of T. It is an o(1) operation.
- TryPop (T) :- public bool TryPop (out T result);Returns true if element present at the top of the stack otherwise false if stack is empty. In out param, set top element of the stack if element present and remove that element from the stack. Set default value of T in out param if stack is empty