Code:
#include<iostream.h>
#include<conio.h>
struct Node {
int a,b;
Node *link;
};
Node *top=NULL,*ptr=NULL;
Node* createNode(int i, int j)
{
ptr = new Node;
ptr->a=i;
ptr->b=j;
ptr->link=NULL;
return ptr;
}
void push(Node *newptr)
{
newptr->link=top;
top=newptr;
}
void pop()
{
if(top==NULL)
cout<<"Stack underflow!!";
else
{
ptr=top;
top=top->link;
delete ptr;
}
}
void displayStack()
{
ptr=top;
cout<<"\n";
while(ptr!=NULL)
{
cout<<"a="<<ptr->a<<", b="<<ptr->b;
if(ptr==top)
cout<<" <-- Stack Top";
ptr=ptr->link;
if(ptr==NULL)
cout<<" <-- Stack bottom";
cout<<"\n";
}
}
int main()
{
char ch='y';
int a, b;
cout<<"Do you want to add a new node?[y/n]";
cin>>ch;
while(ch=='y')
{
cout<<"\nEnter a:";
cin>>a;
cout<<"\nEnter b:";
cin>>b;
push(createNode(a, b));
cout<<"\nDo you want to push another node?[y/n]";
cin>>ch;
}
cout<<"\n\nDisplaying Stack!\n";
displayStack();
cout<<"\nDo you want to pop a node?[y/n]";
cin>>ch;
while(ch=='y')
{
pop();
cout<<"\nDo you want to pop another node?[y/n]";
cin>>ch;
}
cout<<"\n\nDisplaying Stack!\n";
displayStack();
cout<<"\nPress any key to exit..";
getch();
return 0;
}
Output:
Do you want to add a new record?[y/n]y
Enter a:<any num 1>
Enter b:<any num 2>
Do you want to add another record?[y/n]y
Enter a:<any num 3>
Enter b:<any num 4>
<..add as much nodes as you want..>
Do you want to add another record?[y/n]y
Enter a:<any num m>
Enter b:<any num n>
Do you want to add another record?[y/n]n
Displaying Stack!
a=<num m>, b=<num n> <-- Stack Top
<...no.of records you added in the above format : a=<num p>, b=<num q> .....>
a=<num 3>, b=<num 4>
a=<num 1>, b=<num 2> <-- Stack bottom
Do you want to pop a record?[y/n]y
<..pop as much nodes as you want..>
Do you want to pop another record?[y/n]n
Displaying Stack!
a=<num x>, b=<num y> <-- Stack Top
<...no.of records you added - no.of records in the above format : a=<num p>, b=<num q> .....>
a=<num 1>, b=<num 2> <-- Stack bottom
Press any key to exit...
**msg me if any you've any problem; esp. output..**