How to implement stack using using linked list in C++

In this tutorial, we will learn how to implement a stack using a linked list in the C++ programming language.

The stack is one of the most important data structure that is used in software development. One such usage of the stack is in implementing the linked list.

Stack implementation using linked list in C++

A stack data structure can be implemented by using a linked list data structure. The stack implemented using a linked list can work for a large number of values. That means, stack implemented using the linked list works for the variable size of data. So, there is no need to fix the size at the beginning of the implementation.

stack using linkedlist pic1

This implementation is very much helpful in organizing as many values as we want.

TYPES OF OPERATIONS:
1. PUSH: Inserting an element on to the stack.

2.POP: Deletion of an element from the stack

3.Display: Display the current elements which are currently present in the stack.

//stack implementation using linked list
#include<iostream>
#include<malloc.h>
using namespace std;
struct Node{
  int data;
  struct Node *next;
  
};

struct Node *head=NULL,*tail=NULL;

void push()
{
  struct Node *newNode;
  newNode=(struct Node*)malloc(sizeof(struct Node));
  cout<<"ENter data:";
  cin>>newNode->data;
  newNode->next=head;
  
  if(head==NULL)
  {
      head=tail=newNode;
  }
  else
  {
    newNode->next=head;
    head=newNode;
  }
}

void pop()
{
  struct Node *temp;
  if(head==NULL)
  {
    head=tail=NULL;
  }
  else
  {
    temp=head;
    head=head->next;
    free(temp);
  }
}

void display()
{
  struct Node *temp;
  if(head==NULL)
  {
    cout<<"Stack is an underflow";
    return;
    
  }
  else
  {
    temp=head;
    while(temp!=NULL)
    {
      cout<<temp->data<<"\t";
      temp=temp->next;
    }
  }
}
int main()
{ 
   push();
   cout<<"After the first PUSH operation list is :";
   display();
   cout<<"\n";
   push();
   cout<<"After the second PUSH operation list is :";
   display();
   cout<<"\n";
   pop();
   cout<<"After the first POP operation :";
   display();
   cout<<"\n";
     pop();
   cout<<"After the second POP operation :";
   display();
return 0;
}
OUTPUT:
Enter data: 4

After the first PUSH operation list is: 4

Enter data: 5

After the second PUSH operation list is: 5 4

After the first POP operation: 4

After the second POP operation list is: stack is an underflow

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *