×

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

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.