Page 47 - Data Structures Interactive Book
P. 47

5.3   Operations on Stacks


                       The operations on stacks define how this data structure behaves and ensure that it

               follows  the  Last-In,  First-Out  (LIFO)  principle.  Each  operation  manipulates  the  stack  in  a
               specific way and understanding them is essential for applying stacks in practical scenarios

               such as expression evaluation or recursion.




              5.3.1  Push Operation


                       The push operation adds a new element to the top of the stack. In an array-based

               implementation, this involves incrementing the top index and storing the new value at that

               position. In a linked list implementation, a new node is created and linked to the existing top

               node. If the stack is already full (in arrays), an overflow occurs, which must be handled to

               prevent errors. Push is fundamental because it builds the stack structure step by step.


              5.3.2  Pop Operation

                       The pop operation removes the element currently at the top of the stack. In arrays,

               this means decrementing the top index, while in linked lists it involves deleting the top node

               and updating the pointer to the next node. If the stack is empty, a stack underflow occurs,
               which is an error condition. Pop is crucial for reversing actions or retrieving the most recent

               data stored.


              5.3.3  Peek/Top Operation


                       The peek (or top) operation allows the programmer to view the element at the top of
               the stack without removing it. This is useful for checking the current state of the stack, such

               as when evaluating mathematical expressions or verifying balanced symbols. Peek provides

               insight into the stack’s contents while preserving its structure.


              5.3.4  Checking for Empty and Full Conditions

                       Before performing push or pop, it is important to check whether the stack is empty or

               full. In arrays, the stack is full when top == MAX-1 and empty when top == -1. In linked lists,


                                                             47
   42   43   44   45   46   47   48   49   50   51   52