Posts

Search

02x04 - The Queue Data Structure

Queue : Definition : a list of data items, commands, etc., stored so as to be retrievable in a definite order, usually the order of insertion.
A queue is a data structure based on the concept FIFO - First In First Out.

Your task is to implement a queue using arrays.

Your implementation must include the following functionalities :

int queue[] - global array to maintain queue data
int top - global variable to maintain index to queue top
int bottom - global variable to maintain index of queue bottom
void push(int element) - push element to the back of the queue
void pop() - remove one element from front of queue
int empty() - returns 1 if queue is empty and zero otherwise

You are allowed to add global variables/arrays to the body of the code.
All the functions must have an O(1) running complexity.
You are not responsible for taking any input or output.
You are not supposed to modify any part of the code except the BODY of the code.
Only edit the body of the code and implement the required functions with the prototypes as given above.

INPUT

Not Needed

OUTPUT

Not Needed

Sample Input 0

10
push 1
push 2
push 3
push 4
pop
top
pop
top
pop
top

Sample Output 0

2
3
4

Solution :
//HEAD

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"

//BODY

int queue[500005], front=-1, rear=-1;
void push(int add_item)
{
     if (front == - 1)
        front = 0;
        rear = rear + 1;
        queue[rear] = add_item;
}
void pop()
{
        //queue[front];
        front = front + 1;
}
int top()
{
    return queue[front];
}
int empty()
{
    if (front == - 1 || front > rear)
    {
        return 1;
    }
    else 
        return 0;
}

// TAIL

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        char s[50];
        int x;
        scanf(" %s", s);
        if (s[0] == 't')
        {
            if (empty()) printf("Invalid\n");
            else                
                printf("%d\n", top());
        }
        else if (s[0] == 'p' && s[1] == 'o')
        {
            if (empty()) printf("Invalid\n");
            else    pop();
        }
        else
        {
            scanf(" %d", &x);
            push(x);
        }
    }
    return 0;
}