Apple Interview Question
Software Engineer / DevelopersHave a start_index and end_index. Insert at end_index and retrieve data at start_index. Increment start_index at every retrieval and increment end_index at every insertion.
Note: set end_index = end_index % (size of array) so that it implements the wrap around and also makes sure that end_index does not overflow the size of int.
//queue using array
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 5
int i,rear,front,item,s[SIZE];
void insert(int item,int s[]);
void del(int s[]);
void display(int s[]);
void main()
{
int ch;
clrscr();
front=0;
rear=-1;
do
{
printf("\n\n 1.INSERTION \n 2.DELETION \n 3.EXIT \n");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\t INSERTION \n");
if(rear>=SIZE-1)
{
printf("\t\nQUEUE IS FULL\n");
}
else
{
printf("\nENTER AN ELEMENT : ");
scanf("%d",&item);
insert(item,s);
}
display(s);
break;
case 2:
printf("\n\t DELETION \n");
if(front>rear)
{
printf("\t\nQUEUE IS EMPTY\n");
}
else
{
del(s);
}
display(s);
break;
}
}while(ch!=3);
getch();
}
void insert(int item,int s[])
{
if(rear<SIZE)
{
rear=rear+1;
s[rear]=item;
}
}
void del(int s[])
{
int i;
item=s[front];
for(i=0;i<=rear;i++)
s[i]=s[i+1];
rear--;
printf("\n DELETED ELEMENT IS %d\n\n",item);
}
void display(int s[])
{
printf("\n");
for(i=front;i<=rear;i++)
{
printf(" \t %d",s[i]);
}
}
take care of overflow and underflow condition by checking front and rear pointers
- Anonymous January 28, 2011