Write a function that sorts the distinct elements of a queue of integers in such a way that :

  • Even elements are in the same order at the beginning of the queue.
  • Odd elements are in reverse order at the end of the queue.

Use only the ADT operations exposed in class.

Example: After sorting, the following queue

\(\begin{array}{|c|c|c|c|c|c|c|c|c|} \hline
2 & 5 & 8 & 3 & 9 & 6 & 4 & 1 & 7 \\ \hline
\end{array}\)

becomes

\(\begin{array}{|c|c|c|c|c|c|c|c|c|} \hline
2 & 8 & 6 & 4 & 7 & 1 & 9 & 3 & 5 \\ \hline
\end{array}\)


Difficulty level
Video recording
This exercise is mostly suitable for students
void sort(queue *q)
{
	queue L;
	stack R;
	element e;

	L=CreateQueue();
	R=CreateStack();


	while(Front(*q,&e))
	{
		DeQueue(q);
		if(e%2==0)
		{
			EnQueue(&L,e);
		}
		else
		{
			Push(&R,e);
		}
	}
	
	while(Front(L,&e))
	{	
		DeQueue(&L);
		EnQueue(q,e);
	}
	
	while(Top(R,&e))
	{
		Pop(&R);
		EnQueue(q,e);
	}
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Transpose of a matrix using an iterative function