1.stack: LIFO (Last in First Out)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

1.

Stack

 LIFO (last in first out)


1.Stack

 Managing Top element


1.Stack: implement using array
#define MAX 10
void main()
{
int stack[MAX];
int top = -1;
push(stack,top, 10 );

pop(stack,top,value);
int value;

cout<<value;
}
1.Stack: implement using array

void push(int stack[], int &top, int value)


{
if(top < MAX )
{
top = top + 1;
stack[top] = value;
}
else
cout<<"The stack is full";
}
1.Stack: implement using array

void pop(int stack[], int &top, int &value)


{
if(top >= 0 )
{
value = stack[top];
top = top - 1;
}
else
cout<<"The stack is empty ";
}
2.QUEUE

 FIFO (first in first out)


2.QUEUE: implement using array

A circular queue
2.QUEUE: implement using array
#define MAX 10
void main()
{
int queue[MAX];
int bottom,top,count=0;
bottom=top=-1;

enqueue(queue,count,top, 100 );
int value;
dequeue(queue,count,bottom,top,value);

}
2.QUEUE: implement using array

void enqueue(int queue[],int &count, int &top, int value)


{
if(count< MAX)
{
count++;
top= (top +1)%MAX;
queue[top] = value;
}
else
cout<<"The queue is full";
}
2.QUEUE: implement using array
void dequeue(int queue[], int &count,int &bottom,int top, int
&value)
{
if(count==0)
{
cout<<"The queue is empty";
exit(0);
}

bottom = (bottom + 1)%MAX;


value = queue[bottom];
count--;
}
3. Application of stack, queue

 Stack: Expression evaluation


– a*(b–c)/d => abc–*d/
 Queue: priority queues
Exercise:

 Implement: 5 sort algorithms


 Implement stack, queue using array
– Menu with 4 choices
 Add, remove, display, exit

You might also like