Stack Using Pointer C++

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 6

#include<iostream.

h>

#include<conio.h>

#include<alloc.h>

class stack

public:

struct node

int no;

node *next;

};

node *s,*p;

int m,n;

char yes;

stack()

s->next=NULL;

void push(int,node *);

void pop(node *);

void select();

int top(node *);

void print();

int isempty(node *);

void input();
}o;

void stack::push(int x,node *s)

node *tmpcell;

p=s;

tmpcell=((node *)(malloc(sizeof(node))));

if(tmpcell==NULL)

cout<<"Out of space.\n";

else

tmpcell->no=x;

tmpcell->next=s->next;

s->next=tmpcell;

m++;

int stack::top(node *s)

if(!isempty(s))

cout<<"First element in the stack is : "<<s->next->no<<endl;

return s->next->no;

}
cout<<"Empty Stack.\n";

return 0;

void stack::pop(node *s)

node *firstcell;

if(isempty(s))

cout<<"Empty Stack.\n";

else

firstcell=s->next;

s->next=s->next->next;

cout<<"The Poped element is : "<<firstcell->no<<endl;

delete(firstcell);

m--;

int stack::isempty(node *s)

return s->next==NULL;

void stack::select()
{

int k,p,e,d,f;

do

cout<<"\n1.Push\t2.Pop\t3.Top\t4.Display\n\n";

cout<<"Enter your option : ";

cin>>k;

switch(k)

case 1:

if(m==n)

cout<<"Stack is full.\n";

else

cout<<"Enter the no to push : ";

cin>>e;

push(e,s);

print();

break;

case 2:

pop(s);

break;

case 3:

top(s);
break;

case 4:

print();

break;

cout<<"\nDo u want to continue y/n : ";

cin>>yes;

while(yes=='y');

void stack::print()

p=s;

if(p->next==NULL)

cout<<"The stack is empty.\n";

else

cout<<"The elements in the stack are...\n";

while(p->next!=NULL)

p=p->next;

cout<<"|"<<p->no<<" |"<<endl;

cout<<"|---|\n";

}
}

void stack::input()

cout<<"Enter the capacity of the stack : ";

cin>>n;

int main()

clrscr();

o.input();

o.select();

getch();

return 0;

You might also like