Search code examples
algorithmqueuepseudocode

Queue Question for an Algorithms Assignment


I'm trying to figure this out,

'Write the pseudo code for an algorithm isQSimilar(Q1,Q2) to check whether two queues, Q1 and Q2, are similar or not. (i.e. same elements in both queues and the same order of elements) At the end of the comparison, both queues should look unchanged. The only basic operations that you can use on the queues are the following: addQueue(), deleteQueue(), Qsize(), Rear() and Front().'

So what I have so far,

isQsimilar(Q1,Q2)

char check1;
char check2;

int n = Q1.Qsize();
int i = Q2.Qsize();

if (n != i)
    return false;
else
    while (n > 0)
    {
        check1 = Q1.front();
        check2 = Q2.front();

        if (check1 != check2)
            return false;

        Q1.deleteQueue(check1);
        Q2.deleteQueue(check2);

        check1 = Q1.rear();
        check2 = Q2.rear();

        Q1.addQueue(check2);
        Q2.addQueue(check2);

        n--;
    }

return true;

I'm not sure if I'm using the operations correctly or if what I'm doing is remotely correct. Am I in the right direction or am I missing something?

Thank you in advance.


Solution

  • You don't need to check rear elements. I assume that front() only peeks front elements without removing while deleteQueue() removes front element from the queue

    check1 = Q1.front();
    check2 = Q2.front();
    if (check1 != check2)
        return false;
    
    Q1.deleteQueue();
    Q2.deleteQueue();
    
    Q1.addQueue(check1);
    Q2.addQueue(check2);