C++ program for linked stack
Linked stack
Using a linked list is one way to implement a stack so that it can handle essentially any number of elements.
Program:
#include<iostream>using namespace std;
struct node{
int info ;
node *next ;
}*t;
node *top=NULL;
void push(int n)
{node *tmp=new node;
tmp->info=n;
tmp->next=top;//Assigns next pointer of top to tmp
top=tmp;//assigns address of tmp to top
}
void display()
{ node *f=top;
while(f!=NULL)
{cout<<f->info<<"->";
f=f->next;}
cout<<"!!!";
}
void pop()
{
node *tmp=new node;
tmp=top;
top=top->next;//top becomes the next node
delete tmp;
}
main()
{int val,p,ch,val1;
char c;
node *t;
do{cout<<"Enter the info to create new node :";
cin>>val;
push(val);
cout<<"Want to add more : ";
cin>>c;
}while(c=='y'||c=='Y');
cout<<"Enter your choice \n1.Push \n2.Pop\nChoice:" ;
cin>>ch;
switch(ch)
{case 1:cout<<"Enter value you want to insert";
cin>>val1;
push(val1);
break;
case 2:pop();}
cout<<"Display ";
display();
}

Comments
Post a Comment