DSA DAY 3 - Stacks and Queues
DSA DAY 3 - Stacks and Queues
Circular Queue
Deque
Priority Queue
WHAT IS A STACK?
• Linear List in which insertions and deletions are
allowed only at one end, called top of the stack
• LIFO: Last In First Out
• Example: Stack of trays in Cafeteria
• Insertion: push()
• Deletion: pop()
HOW
DOES A
STACK
WORK?
ARRAY •int stack_arr[MAX];
IMPLEMENTATION •int top = -1;
OF STACK
PUSH
int peek()
{
if( isEmpty() )
{
printf("Stack Underflow\n");
exit(1);
}
return stack_arr[top];
}/*End of peek()*/
ISEMPTY
int isEmpty()
{
if( top == -1 )
return 1;
else
return 0;
}/*End of isEmpty*/
ISFULL
int isFull()
{
if( top == MAX-1 )
return 1;
else
return 0;
}/*End of isFull*/
DISPLAY
void display()
{
int i;
if( isEmpty( ) )
{ printf("Stack is empty\n");
return;
}
printf("Stack elements :\n\n");
for(i=top;i>=0;i--)
printf(" %d\n", stack_arr[i] );
printf("\n");
}/*End of display()*/
struct node
LINKED LIST {
int info;
IMPLEMENTATION struct node *link;
}*top=NULL;
PUSH
void push(int item)
{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node));
if(tmp==NULL)
{
printf("Stack Overflow\n");
return;
}
tmp->info=item;
tmp->link=top;
top=tmp;
}/*End of push()*/
POP
int pop()
{ struct node *tmp;
int item;
if( isEmpty() )
{ printf("Stack Underflow\n");
exit(1);
}
tmp=top;
item=tmp->info;
top=top->link;
free(tmp);
return item;
}/*End of pop()*/
PEEK
int peek()
{
if( isEmpty() )
{
printf("Stack Underflow\n");
exit(1);
}
return top->info;
}/*End of peek() */
ISEMPTY
int isEmpty()
{
if(top == NULL)
return 1;
else
return 0;
}/*isEmpty()*/
DISPLAY
void display()
{ struct node *ptr;
ptr=top;
if(isEmpty())
{ printf("Stack is empty\n");
return;
}
printf("Stack elements :\n\n");
while(ptr!=NULL)
{ printf(" %d\n",ptr->info);
ptr=ptr->link;
}
printf("\n");
}/*End of display()*/
• A linear list in which elements can be inserted only at one end called
rear of the queue and deleted at the other end called front.
int peek()
{
if( isEmpty() )
{
printf("Queue Underflow\n");
exit(1);
}
return queue_arr[front];
}/*End of peek()*/
ISEMPTY
int isEmpty()
{
if( front==-1 || front==rear+1 )
return 1;
else
return 0;
}/*End of isEmpty()*/
ISFULL
int isFull()
{
if( rear==MAX-1 )
return 1;
else
return 0;
}/*End of isFull()*/
DISPLAY
void display()
{
int i;
if ( isEmpty() )
{
printf("Queue is empty\n");
return;
}
printf("Queue is :\n\n");
for(i=front;i<=rear;i++)
printf("%d ",queue_arr[i]);
printf("\n\n");
}/*End of display() */
struct node
LINKED LIST {
int peek()
{
if( isEmpty( ) )
{
printf("Queue Underflow\n");
exit(1);
}
return front->info;
}/*End of peek()*/
ISEMPTY
int isEmpty()
{
if(front==NULL)
return 1;
else
return 0;
}/*End of isEmpty()*/
DISPLAY
void display()
{ struct node *ptr;
ptr=front;
if(isEmpty())
{ printf("Queue is empty\n");
return;
}
printf("Queue elements :\n\n");
while(ptr!=NULL)
{ printf("%d ",ptr->info);
ptr=ptr->link;
}
printf("\n\n");
}/*End of display()*/
CIRCULAR QUEUE