×

Stack in C++

Stack:

The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract Data Type used to store a collection of objects.

Various operations are uniquely associated with stacks. They are namely push, pop, and peek.

Let's look out what is a push, pop and peek or top, and isEmpty.

Push: When an element is pushed inside a stack, it is called Push

      operation.

Pop: When an element is removed from the top of the stack, it is

     called as Pop operation.

Peek or Top: This return top element of the stack.

isEmpty: It return true if stack is empty, else return false.

Pre-Requisites:

Before understanding stacks, one must be familiar with the below fundamentals.

  1. Conditional statements like if, else.
  2. Pointers.
  3. Loops like for, while and do while.
  4. Arrays and string primarily.
  5. One object oriented programming language like C++ or Java.

All the above operations have 0(1) complexity and no loop is used.

Let us look at basic syntax of stack operations that we involve while implementing it.

Push:

 void push(int information) {
    if(isNotFull()) {
       top = top + 1;  
       stack[top] = information;
    } else {
       printf("Stack is full.");
    }
 } 

Pop:

 int pop(int data) {
    if(isNotempty()) {
       information = stack[top];
       top = top - 1;  
       return information;
    } else {
       printf("Stack is empty.\n");
    }
 } 

Peek or Top:

 int peekOrTop()
 {
    return stack[top];
 } 

isEmpty:

 bool isEmpty()
 {
    if(top == -1)     //-1 denotes empty
       return true;
    else
       return false;
 } 

The above pseudo codes can be combined to show operations in the following code below.

 #include <bits/stdc++.h>
 using namespace std;
 #define max 1000
 class Stack {
     int top;
 public:
     int a[max];
     Stack() { top = -1; }
     bool push(int y);
     int pop();
     int peek();
     bool isEmpty();
 };
 bool Stack::push(int y)
 {
     if (top >= (max - 1)) {
         cout << "Stack Overflow";
         return false;
     }
     else {
         a[++top] = y;
         cout << y << " is pushed inside stack \n";
         return true;
     }
 }
 int Stack::pop()
 {
     if (top < 0) {
         cout << "Stack Underflow";
         return 0;
     }
     else {
         int x = a[top--];
         return x;
     }
 }
 int Stack::peek()
 {
     if (top < 0) {
         cout << "Stack is Empty";
         return 0;
     }
     else {
         int x = a[top];
         return x;
     }
 }
 bool Stack::isEmpty()
 {
     return (top < 0);
 }
 int main()
 {
     class Stack s;
     s.push(100);
     s.push(200);
     s.push(300);
     cout << s.pop() << "Popped out from stack\n";
     return 0;
 } 

Output:

Stack in C++

Explanation:

In the above code, we have used an object-oriented programming method so that we can handle code complexity and make it more readable.

Let us take into consideration the below algorithms to understand the logic behind our code.

START

  1. Top = 0
  2. Exit

PUSH(STACK,TOP,MAX,ITEM)

  1. Top = max then

    B. Print “Stack full”;

    C. Exit out of the stack.

    Otherwise

  • Top: = Top + 1;        //increasing top
  • Check Stack(Top)= ITEM;
  • End IF
  • Exit

POP_STACK(STACK,TOP,ITEM)

A. IF Top = zero

        Print “Empty Stack”;

        Exit;

  • Otherwise

        ITEM: =Stack (Top);

        Top:=Top – 1;

  •  End IF
  •  Exit

END

These algorithms are usually followed in the above code to show how the push and pop operations are commonly carried out.

Applications of Stacks

The applications of stacks are listed below:

  1. Memory management:

The continuous memory blocks help in memory assignment when it takes place. With stack, we do it functionally and the size of the memory to be allocated will be already known by the compiler. When a functional call is executed, memory is allocated and de-allocated when it is already used. These executions happen at defined intervals so that the users do not have to worry about memory management.

  • Evaluating Expressions and Conversions:

Expressions in stacks primarily work on the operator precedence. Say (2*2)+4 will give us 8 since the * or the parenthesis has higher priority. So, they can also be used for parenthesis matching in an expression when a user has not defined the correct order.

  • Backtracking Occurrences:

For complex algorithms like the 8 -Queens problem of Knights Tour problem, backtracking is specifically used to get to the last point where we found the value. Thus, a stack is very efficient in providing backtracking methods. It was used to get back from the current state we may need the previous state and then got into some other paths.

Insights:

In real-world applications, Stack plays a crucial role in particular. From the application perspective stacks are most applicable in the scientific calculations. The undo option in text editors use the stack to roll back to the previous elements.

In programming, it may be used to reverse a word, language processing, defining, and keeping records in a database, and also used to support recursion.


Related Topics

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.