The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end is removed first, and the element that is added first is removed at the end. There is only one end to insert and remove the element in the stack called the top end.

Stack

Example:

A good real-life example of a stack is the pile of dinner plates. When you have to take one plate from a pile, you pick the topmost plate and then the next plate. The last plate is picked at the end, which is placed first in a pile. The last plate is known as the base plate in the stack.

Stack

Stack operations

There are four types of operations in the stack.

  1. Push
  2. Pop
  3. Peek
  4. Update

Push: Push operation is used to insert a new element in the stack. Push operation is shown in the figure below.

Stack

Pop: Pop operation is used to delete an element in the stack. Pop operation is shown in the figure below.

Stack

Peek: When the data is received from a particular location in the stack, that operation is called peep operation.

Update: When the value of an element is changed in the stack, that operation is called update operation.

Overflow & Underflow Conditions

If the stack is empty and trying to delete an element from it, that situation is called underflow. If the stack is full and trying to add a new element to it, that situation is called overflow.

Applications of stack

  1. Expression evaluation: Stack is used to evaluating the prefix, postfix, and infix expressions.
Infix notationPrefix notationPostfix notation
A + B+ A BA B +
(A – C) * B*- A C BA C – B *
A + (B * C)+ A * BCA B C * +
(A + B) / (C + D)/ + A B – C DA B + C D – /
(A + (B * D)) / (C – (D * B))/ + A * B C – C * D BA B C * + C D B * – /
  • Expression conversion: An expression is represented in the prefix, postfix, or infix notation. The stack is used to convert the form of one expression to another form.
  • Syntax parsing: Many compilers use the stack to parsing the syntax expressions.
  • Memory management: It is also used in memory management.
  • Variable tracking: Stack is also used to track local variables in runtime.
  • Parenthesis checking: Stack is also used to check whether parenthesis is correctly open and closed or not.
  • String reverse: Stack is also used to reverse the string. In the string, we push the characters into the stack one by one and then pop the characters from the stack one by one.
  • Undo: Stack is also used to undo in text-editor.

Implementation in C language

Pin It on Pinterest

Share This