Stack data structure | Introduction and Stack operations

05 min read

Stack is a FILO (First In Last Out) data structure where the element that is added first will be deleted last. Stack operations like insertion (PUSH) and deletion of elements (POP) are performed at the top of the stack. The elements in a stack are arranged sequentially and hence stacks are said to be linear data structures.

The practical examples of stacks are:

  • Arrangement of plates.
  • Arrangement of books in a cupboard.
  • Wearing or removing bangles from hands.

 

Various Stack Operations

The most basic stack operations in the data structure are the following

  • push() - Adds an element at the top of the stack. If the stack is full, then it is an overflow.
  • pop() - Deletes an element from the top of the stack. If the stack is empty, then it is an underflow.
  • peek() - Displays the topmost element in the stack.

stack data structure in c

1) push() 

  • Check if the stack is full.
  • If the stack is full, then display "Stack overflow".
  • If the stack is not full, increment top to the next location.
  • Assign data to the top element.
Algorithm_push()

If TOP >= SIZE – 1 then  //  Stack Overflow indicating that the Stack is FULL.
TOP = TOP + 1
STACK [TOP] = ELEMENT

2) pop()

  • Check if the stack is empty.
  • If the stack is empty, then display "Stack Underflow".
  • If the stack is not empty, copy top in a temporary variable.
  • Decrement top to the previous location.
  • Delete the temporary variable.
Algorithm_pop()

If TOP = -1 then  //  Stack Underflow indicating that the Stack is EMPTY.
Return STACK [TOP]
TOP = TOP - 1

3) peek()

  • Print the top most element from the stack.
Algorithm_peek()

Return STACK [TOP]

stack operations in c

Representation of stacks

Stacks can be represented using both arrays and linked lists.

Stacks using arrays

stack array

  1. Initially, the topmost element from the array is 5.
  2. Performing a pop operation, deletes the topmost element 5 from the array and makes 4 as the topmost element.
  3. Now, on performing push operation to add element 5, the element is added and is made as the topmost element. 

Stacks using Linked Lists

stack linked list

  1. Initially, the topmost element in the linked list is 4.
  2. Performing a pop operation, deletes the topmost element 4 from the list and makes 3 as the topmost element.
  3. Now, on performing push operation to add element 4, the element is added and is made as the topmost element. 

 

Learn more:

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error