stack_and_queues_using_class_templates

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Stack using Class Templates

#include<iostream.h>

#include<conio.h>

template <class T>

class stack

public:

T st[100];

int top,size;

stack()

cout<<"\n Enter Size of your stack :";

cin>>size;

top=-1;

void push(T x)

st[++top]=x;

T pop()

return(st[top--]);

void display()

{
int i;

for(i=top;i>=0;i--)

cout<<endl<<" "<<st[i];

};

void main()

int n,f=0;

clrscr();

stack <float>s1;//change float to any data type for Eg,<char> for queue which stores character
type of data

float x;//as above also change this to the same as above

while(f!=1)

cout<<"\n\n 1)PUSH\n 2)POP\n 3)Display\n 4)Exit\n Enter an option :";

cin>>n;

switch(n)

case 1:

if(s1.top < s1.size - 1)

cout<<"\n Enter Element :";

cin>>x;

s1.push(x);
}else

cout<<"\n --OVERFLOW--\n";

break;

case 2:

if(s1.top!=-1)

cout<<"\n Deleted Element :"<<s1.pop()<<endl;

}else

cout<<"\n --UNDERFLOW--\n";

break;

case 3:

if(s1.top!=-1)

cout<<"\n Elements in stack are:\n";

s1.display();

}else

cout<<"\n No elements in stack\n";

break;

case 4:
f=1;

break;

getch() ;

Queues using class templates

#include<iostream.h>

#include<conio.h>

template <class T>

class queue

public:

int rear,front;

int size;

T Q[100];

queue()

rear=front=-1;

cout<<"\n Enter size of your queue:";

cin>>size;

}
void enqueue()

if(rear < size-1)

if(rear==-1)

front=0;

cout<<"\n Enter Element :";

T x;

cin>>x;

Q[++rear]=x;

}else

cout<<"\n --OVERFLOW--\n";

void dequeue()

if(rear == -1)

cout<<"\n --UNDERFLOW--\n";
}else

cout<<"\n Deleted Element :"<<Q[front];

if(rear==0 && front==0)

rear=front=-1;

}else

for(int i=front;i<rear;i++)

Q[i]=Q[i+1];

rear--;

void display()

if(rear!=-1)

cout<<"\n Elements in Queue are:\n";

int i;
cout.precision(2); //just in case of float

for(i=front;i<=rear;i++)

cout<<" "<<Q[i]<<" -> ";

}else

cout<<"\n No elements in Queue\n";

};

void main()

int n,f=0;

clrscr();

queue <float>s1;

while(f!=1)

cout<<"\n\n 1)Enqueue\n 2)Dequeue\n 3)Display\n 4)Exit\n


Enter an option :";

cin>>n;

switch(n)
{

case 1:

s1.enqueue();

break;

case 2:

s1.dequeue();

break;

case 3:

s1.display();

break;

case 4:

f=1;

break;

getch();

You might also like