A Stack is a linear data structure where the elements are inserted and removed in a particular order. Stack examines the item most recently added - LIFO (Last In, First Out).
A Stack can be implemented with either an array or a linked list.
Fixed Size. It has a predefined capacity and cannot be re-sized dynamically in runtime. If the stack is full, pushing a new element will cause an overflow error.
Dynamic size. It can adjust its capacity based on the number of stored elements. It can be implemented using a re-sizable array or a linked list.
To implement the Stack, we need to maintain a pointer referring to the top element.
publicclassStackArray<T>{privateT[]stack;privateintheadIndex=-1;// Initialize stack with a custom capacitypublicStackArray(intcapacity){stack=(T[])newObject[capacity];}// Insert a new element onto the stackpublicvoidpush(Tvalue){stack[++headIndex]=value;}// Retrieve the top element and delete itpublicTpop(){Tvalue=stack[headIndex];stack[headIndex--]=null;returnvalue;}// Retrieve the top element without deleting itpublicTpeek(){returnstack[headIndex];}}
publicclassStackLinkedList<T>{privateclassNode{publicTvalue;publicNodenext;}privateNodehead;// Insert a new element onto the stackpublicvoidpush(Tvalue){Nodenode=newNode();node.value=value;node.next=head;head=node;}// Retrieve the top element and delete itpublicTpop(){Tvalue=head.value;head=head.next;returnvalue;}// Retrieve the top element without deleting itpublicTpeek(){returnhead.value;}}
👉
The complete StackArray and StackLinkedList implementations are available here.