Home Data Structures Stack Data Structure Tutorial and Implementation

Stack Data Structure Tutorial and Implementation

The stack is a Data Structure that supports insertion and deletion of elements in a particular order, i.e, LIFO (Last In First Out). Whenever any element is inserted it goes to the top of the stack and the element which is inserted at the last (element at the top of the stack) will be removed at first.

Basic Stack Operation:

PUSH: Push operation is used to insert an element into the stack data structure. It pushes/inserts an element at the top of the stack. If the stack is full, it will return Stack Overflow. If expects an element to be inserted as an input parameter.

Algorithm:
push(int element):
    if(tos == max_size):
        printf(“stack overflow”);
    else:
       tos++;
       stack[tos] = element;
       

POP: Pop operation is used to delete an element from the top of the stack. If the stack is empty, it will return stack underflow.

Algorithm:
pop():
   if(top==-1):
       printf(“Stack Underflow”)
    else:
       stack[tos] == 0;
       tos–;

Note: tos is a variable that points to the top of the stack.

Time Complexity Of Stack Operation

  1. Push Operation: O(1)
  2. Pop Operation: O(1)
  3. Search an Element: O(N)

Implementation of Stack in CPP

Output:
Stack content is:
1 5 7 9 10 12 15
Stack content is:
1 5 7 9 10

Subscribe to our weekly newsletter

Join our community of 1000+ developers and stay updated with the fast moving world of computer science

We promise, we won't spam
Even we hate spam as much as you hate them

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here