×

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows LIFO (Last In First Out) or FILO (First In Last Out).

LIFO: The element inserted at the end will be deleted first.

FILO: The element inserted at the first position will be deleted last.

Both LIFO and FILO mean the same here.

How to create a stack in C++

Applications of Stack Data Structure

1. Expression conversion

Postfix, prefix, and infix expression conversions are implemented using a stack. With the help of stack operations, those conversions will be performed.

2. Backtracking

Stack helps backtrack from the current position to the previous position.

3. String Reversal

Stack helps us in reversing a string. First, we store all the characters of a string into the stack, and then we pop those characters from the stack. This operation will result in reversing a string.

4. Algorithms

Many algorithms are implemented using stack.

5. Recursion

Recursion uses the stack for its base case and the multiple function calls that are made.

6. Memory Management

Stack plays a vital role in Memory management, where all essential operations by an operating system are performed through memory management.

Implementation/Creation

In C++, a stack can be implemented or created without STL and STL. Here STL is known as Standard Template Library. The only difference is that STL contains all inbuilt libraries and methods which help implement a stack.

Before creating a stack, some terminology is essential for us to understand stack operations.

Some points to be noted:

  • Push: With this operation, a new element is added to the stack's top, replacing the existing or previous top element. Followed by increasing the size of the stack by one.
  • Pop: This operation helps in deleting the top element from the stack and reduces the size of the stack by one each time.
  • Peek: The top element from the stack is returned by this operation.
  • Size: Size is used to determine how many elements are present in the stack overall.
  • Display: Display is used to print the elements in the stack in order, starting from the top to bottom.
  • top = SIZE-1 means stack is full and top = -1 means stack is empty.

Let's first see the creation of a stack without STL

Program to create a stack in C++ by using an array without STL

#include<iostream>
using namespace std;
#define SIZE 40
int stack [ SIZE ], top = -1;
void push ( int ele )
{
 if (top == SIZE-1)
 {
 cout<<"Stack Over Flow"<<endl;
 }
 else
 {
 top++;
 stack [ top ] = ele;
 }
}
void pop ( )
{
 if (top==-1)
 {
  cout<<"Stack under-Flow"<<endl;
 }
 else
 {
    int element=stack[top];
  cout<<"Element "<<element<<" popped/deleted Successfully."<<endl;
  top--;
 }
}
void peek()
{
    if(top==-1)
    cout<<"Sorry!there are no elements present in the stack"<<endl;
    else
    cout<<"The top most element in the stack is: "<<stack[top]<<endl;
}
void size()
{
    cout<<"The size of the stack is: "<<top+1<<endl;
}
void displayStack()
{
 int i;
 if ( top == -1 )
 {
  cout<<"Stack is empty, there are no elements present!"<<endl;
 }
 else
 {
  cout<<"The element(s) in the stack are :"<<endl;
  for (int i=top; i>= 0; i--)
   cout<<stack[i]<<endl;
 }
}
int main()
{ 
 int choice, element;
 while(1)
 {
 cout<<"Stack Operations are:"<<endl;
 cout<<"Choice-[1]:Push"<<endl;
 cout<<"Choice-[2]:Pop"<<endl;
 cout<<"Choice-[3]:Peek"<<endl;
 cout<<"Choice-[4]:Size"<<endl;
 cout<<"Choice-[5]:Display Stack"<<endl;
 cout<<"Enter your choice from the above : ";
 cin>>choice;
 switch(choice)
 {
 case 1:
 cout<<"Enter the element to insert into the stack :";
 cin>>element;
 push(element); 
 cout<<"Element "<<element<<" Pushed/Inserted Successfully."<<endl;
 break;
 
 case 2 :
 pop(); 
 break;
 
 case 3 :
 peek(); 
 break;
 
 case 4 :
 size(); 
 break;
 
 case 5 :
 displayStack();
 break;
 
 default:
 return 0;
 } 
 }  
}

Output

How to create a stack in C++

Now, Let's see the creation using STL.

STL is a powerful template library which makes our life easier. It contains almost all inbuilt libraries, methods, functions etc.

Considering the current data structure stack, all the operations we have implemented above, like push, pop, and peek, can be used here directly without any specific implementation.

The only that has to be done is to include this: " #include<bits/stdc++.h " or you can also include " #include<stack> " which is stack specific.

Some points to be noted :

  • push(): : With this operation, a new element is added to the stack's top, replacing the existing or previous top element. Followed by increasing the size of the stack by one.
  • pop(): This operation helps in deleting the top element from the stack and reduces the size of the stack by one each time.
  • top() : The top element from the stack is returned by this operation.
  • size() : Size is used to determine how many elements are present in the stack overall.
  • empty() : It is used to check whether the stack is empty or not.

All the above operations are included in '#include<stack>'. Hence, no specific implementation would be required for them, as we did in the previous program.

Syntax of Stack In STL

stack <type> stackName;

stack is a pre-defined template keyword used to create a stack's object.

type indicates the data type that has to be passed. It denotes a particular data type of the elements stored in the stack, like int, which keep only integers, char that store only characters etc.

stackName indicates the name of the stack object that has been created. We can perform all the stack operations with that particular name.

Program to create a stack in C++ with STL

#include <iostream>
#include <stack>
using namespace std;


// Stack implementation in C++ using ‘std::stack’
int main()
{
    stack<int> st; //Intializing a stack which can store integers.
 
    st.push(10);    // Inserting 10 into the stack
    st.push(20);    // Inserting 20 into the stack
    st.push(30);   
    st.push(40); 
    st.push(50); 
    st.push(60); 
 
    // prints the total number of elements present in the stack
    cout << "The size of the stack is " << st.size() << endl;
 
    // prints the top element of the stack
    cout << "The top element is " << st.top() << endl;
 
    st.pop();       // top elemet 60 will be removed.
    cout<<"Top element Deleted successfully"<<endl;        
    st.pop();     // next top element 50 will be removed.
    cout<<"Next Top element Deleted successfully"<<endl;       
    cout << "The size of the stack is " << st.size() << endl;
 
  while(1)
  {
    if (st.empty()) 
    {
        cout <<"The stack is empty\n";
        break;
    }
    else 
    {
        int ele=st.top();
        cout<<"The element is :"<<ele<<endl;
    }
    st.pop();
  }
   return 0;
}

Output

How to create a stack in C++

Related Topics

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.