Stack using Linked List in DSA C++
by DataFlair Team
Program 1
// Stack Linked List
#include<iostream>
#include<stdio.h>
using namespace std;
class Node
{
int data;
Node *add;
public:
void create();
void push();
void pop();
void display();
};Node *start=NULL,*new1,*temp,*prev1;
void Node::create()
{
int n;
cout<<"\n Enter an element: ";
cin>>n;
start=new Node();
start->data=n;
start->add=NULL;
temp=start;
char choice;
cout<<"\n Want to continue(Y/y) : ";
cin>>choice;
while(choice=='y' ||choice=='Y')
{
cout<<"\n Enter next element: ";
cin>>n;
new1=new Node();
new1->data=n;
new1->add=NULL;
temp->add=new1;
temp=temp->add;
cout<<"\n Want to continue(Y/y) : ";
cin>>choice;
}
}
void Node::display()
{
if(start==NULL)
cout<<" Stack is empty";
else
{
temp=start;
while(temp!=NULL)
{
cout<<temp->data <<" ";
temp=temp->add;
}
}
}
void Node::push()
{
if(start==NULL)
cout<<" Stack not created....";
else
{
int n;
cout<<"\n Enter an element: ";
cin>>n;
new1=new Node();
new1->data=n;
new1->add=NULL;
temp=start;
while(temp->add!=NULL)
{
temp=temp->add;
}
temp->add=new1;
}
}
void Node::pop()
{
if(start==NULL)
cout<<" Stack is empty...";
else
{
temp=start;
while(temp->add!=NULL)
{
prev1=temp;
temp=temp->add;
}
cout<<"Poped element is: "<<temp->data;
prev1->add=NULL;
delete temp;
}
}
int main()
{
int ch;
Node obj;
system("cls");
do
{
cout<<"\n-----------Stack Linked List------------------";
cout<<"\n 1. Create";
cout<<"\n 2. Push";
cout<<"\n 3. Pop";
cout<<"\n 4. Display ";
cout<<"\n 5.Exit";
cout<<"\n------------------------------------------------";
cout<<"\n Enter your choice: ";
cin>>ch;
switch(ch)
{
case 1:obj.create();break;
case 2:obj.push();break;
case 3:obj.pop();break;
case 4: obj.display();break;
case 5:break;
default:cout<<"\n Invalid choice";
}
}while(ch!=5);
return 0;
}
Tags: dsa c++dsa c++ practicaldsa c++ programdsa c++ stack using linked liststack implementation using linked liststack implementation using linked list in dsa c++stack using linked liststack using linked list in c++stack using linked list in dsa c++
DataFlair Team
DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.