Search code examples
crecursionqueuefunction-definition

Problem while transforming an iterative function that prints a Queue into a recursive one


I have this iterative function that display a Queue:

void displayQueue(queue *Q){

     int temp;

     while(!isEmpty(Q)){
         temp = dequeue(Q);
         printf("%d -> ", temp);
         displayQueue(Q);
         enqueue(Q, temp);
     }

     reverse(Q);
}

I would like to make it completely recursive by removing the while loop, this is what i got so far:

void displayQueue(queue *Q){

    if(isEmpty(Q)) return;

    int temp = dequeue(Q);
    printf("%d -> ", temp);
    displayQueue(Q);
    enqueue(Q, temp);
}

The problem is when to call the "reverse(Q)" function which must be called at the end of the printing when the function returns but at that moment Q is empty so it would not be reversed (the printing of the queue causes its inversion)

This is my Queue structure:

typedef struct queue{
  unsigned capacity;
  int size;
  int front;
  int rear;
  int *array;
}queue;

Solution

  • It seems the function should look the following way

    void displayQueue( queue *Q )
    {
        if ( !isEmpty( Q ) )
        {
            int temp = dequeue( Q );
            printf( "%d -> ", temp );
    
            displayQueue( Q );
    
            reverse( Q );
            enqueue( Q, temp );
            reverse( Q );
        }
    }
    

    If you want to avoid to reverse the queue so often then you can write the function with a static variable for example like

    void displayQueue( queue *Q )
    {
        static int state = 0;
    
        if ( !isEmpty( Q ) )
        {
            int to_reverse = state ^ 1;
            if ( to_reverse ) state = to_reverse;
    
            int temp = dequeue( Q );
            printf( "%d -> ", temp );
    
            displayQueue( Q );
    
            enqueue( Q, temp );
    
            if ( to_reverse )
            {
                reverse( Q );
                state = 0;
            }
        }
    }
    

    Without the static variable you can write the function splitting it into two functions. The first one calls a recursive function and reverses the result. The second one is that recursive function that displays the queue.

    For example

    void recursiveDisplayQueue( queue *Q )
    {
        if ( !isEmpty( Q ) )
        {
            int temp = dequeue( Q );
            printf( "%d -> ", temp );
    
            recursiveDisplayQueue( Q );
    
            enqueue( Q, temp );
        }
    }
    
    void displayQueue( queue *Q )
    {
        if ( !isEmpty( Q ) )
        {
            recursiveDisplayQueue( Q );
    
            reverse( Q );
        }
    }