Queue using pointers.


The queue is a basic data structure just like a stack. In contrast to stack that uses the LIFO approach, queue uses the FIFO (first in, first out) approach. With this approach, the first item that is added to the queue is the first item to be removed from the queue. Just like Stack, the queue is also a linear data structure.
In a real-world analogy, we can imagine a bus queue where the passengers wait for the bus in a queue or a line. The first passenger in the line enters the bus first as that passenger happens to be the one who had come first.
PROGRAM:
//Code By Vikas
#include <stdio.h>
#include<stdlib.h>

int *ptr,front,rear,size;
void create();
void push();
void pop();
void display();
void create()
{
    front=-1;
    rear=-1;
}
void push()
{
    int val;
    if(rear==size-1)
    printf("\n queue is full");
    else
    {
        printf("\n Enter a element to push");
        scanf("%d",&val);
        rear++;
        ptr[rear]=val;
    }
}
void pop()
{
    if(front==rear)
    printf("\n queue is Empty");
    else
    front++;
    printf("\n The deleted element is %d",ptr[front]);
    ;
}
void display()
{
    int i;
    if(front==rear)
    printf("\n queue is empty");
    else
    {
    printf("\n Queue is ...\t");
    for(i=rear;i>front;--i)
    printf("%d\n",ptr[i]);
    }
}
void main()
{
    int ch;
    printf("\n Enter the size");
    scanf("%d",&size);
    ptr= (int *)malloc(sizeof(int) * size);

    while(1)
    {
        printf("\n1:Create\n2:Push\n3:Pop\n4:Display\n5:Exit");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:create();
            break;
            case 2:
            push();
            break;
            case 3:
            pop();
            break;
            case 4:
            display();
            break;
            case 5:
            exit(0);
            break;
            
        }
    }
}

Recommended: solve it on “PRACTICE ” first, before moving on to the solution.



Previous Post Next Post