#include<conio.h>
#include<stdlib.h>
#include<process.h>
struct Node
{
int info;
Node *next;
} *top,*newptr,*save,*ptr;
Node *Create_New_Node(int );
void push(Node *);
void display(Node *);
void pop();
int main()
{
clrscr();
top=NULL; //in the begining linked stack is empy, thus pointers are NULL
int inf; char ch='y';
while(ch=='y'||ch=='Y')
{
cout<<"\n Enter information for the new node....";
cin>>inf;
newptr=Create_New_Node(inf);
if(newptr==NULL)
{
cout<<"\n cannot create new node \n";
exit(1);
}
push(newptr);
cout<<"\n Press y to enter more nodes, N to exit()....";
cin>>ch;
}// while end.
do
{
cout<<"\n The stack now is : \n";
display(top);
cout<<"want to pop an element ? (y/n)";
cin>>ch;
if(ch=='y'||ch=='Y')
pop();
}
while(ch=='y'||ch=='Y');
return 0;
}//main end
Node *Create_New_Node(int n)
{
ptr= new Node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void push(Node *np)
{
if(top == NULL) top=np;
else
{ save =top; top=np;
np->next=save;
}
}
void pop()
{
if(top==NULL) cout<<"Underflow";
else
{
ptr=top; top=top->next;
delete ptr;
}
}
void display(Node *np)
{
while(np != NULL)
{
cout<<np->info<<"->";
np=np->next;
}
cout<<" !!! \n";
}
No comments:
Post a Comment