Implement queue using dynamic memory allocation such that the implementation should abide with the following constraints.
- The user should use memory allocation from the heap using \(\texttt{malloc()}\) function. You need to take care of the max value in the queue structure. (You do not need \(\texttt{#define}\)).
- In \(\texttt{EnQueue}\) function, when the queue is full, you should allocate more space using \(\texttt{realloc()}\) function call.
- In \(\texttt{DeQueue}\) function, once you are below half of the capacity of the queue, you need to decrease the size of the queue by half. You should add one more variable \(\texttt{min}\) to queue structure so that you can track the changes in the queue size.
Difficulty level
This exercise is mostly suitable for students
**************************************************
**************************************************
** **
** SOLUTION PROVIDED BY ABBAS KHREISS **
** **
**************************************************
**************************************************
#include<stdio.h>
#include<stdlib.h>
typedef int element;
typedef struct {
element * data;
int size;
} stack;
stack createStack()
{
stack s;
s.size = 0;
return s;
}
int isEmptyStack(stack s)
{
return s.size == 0;
}
int Push(stack * s, element e)
{
element * tmp;
if (s->size == 0)
tmp = (element *)malloc(sizeof(element));
else tmp=(element *)realloc(s->data, sizeof(element)*(s->size + 1));
if (tmp)
s->data = tmp;
else return 0;
s->data[s->size] = e;
++s->size;
return 1;
}
int Pop(stack * s)
{
element * tmp;
if (isEmptyStack(*s))
return 0;
if (s->size == 1)
free(s->data);
else {
tmp = (element *)malloc(s->size-1);
for (int i = 0; i < s->size - 1;i++)
tmp[i] = s->data[i];
free(s->data);
if (!tmp) return 0;
s->data = tmp;
}
--s->size;
return 1;
}
int Top(stack s, element * e)
{
if(isEmptyStack(s))
return 0;
*e = s.data[s.size - 1];
return 1;
}
stack copyStack(stack s)
{
stack s1 = s;
element * tmp = (element *)malloc(s.size*sizeof(element));
for (int i = 0; i < s.size; i++)
tmp[i] = s.data[i];
s1.data = tmp;
return s1;
}
void displayStack(stack s)
{
element e;
while(Top(s, &e))
{
Pop(&s);
printf("|%5d|\n", e);
}
printf("|_____|\n\n");
}
int main()
{
element e;
stack s = createStack();
for (int i = 0; i < 5; i++)
{
Push(&s, i);
displayStack(copyStack(s));
}
printf("---------------------------------------------------\n");
while (Top(s, &e))
{
Pop(&s);
displayStack(copyStack(s));
}
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using the radix sort algorithm