Approach 1)
First, cancel the entire queue (excluding the equality of 21.22, etc.), then cancel each individual block (for example, 21.22, etc.) using the stack. This can be done iteratively.
This is similar to the inverse of the sentence problem (a well-known interview question).
(see the given example and pseudo-code below)
Approach 2)
If you want to absolutely perform recursion, I would suggest you use Queue as auxiliary storage, not a stack.
You insert the block into the auxiliary queue, recursively modify the rest of the list, and then insert the elements back into the main queue.
The code will be something like this (handwavy pseudo)
StrangeReverse(Queue <T> q) { Queue<T> aux; // this removes first block from q, and places them in aux while (elem_of_first_block(q)) { aux.Enque(elem); } // Recursively reverse the rest of the q. StrangeReverse(q); // place the first block back in q, at the end. // in the order they appeared originally. while (aux.HasElements()) { q.Enque(aux.Deque()); } }
A recursive version can be converted to iterative, having a queue stack! You create a queue from each block and add them. Then put the stack, use the queues.
Developed example approach 1
[11, 12, 21, 22, 43, 44]
Discard it (using stack or recursive method)
[44, 43, 22, 21, 12, 11]
Now undo each block:
push 44, the 43.
Stack = [44, 43]. Queue = [22, 21, 12, 11]
Now enque, jumping out of the stack
Stack = [], Queue = [22, 21, 12, 11, 43, 44]
push 22, 21
Stack = [22, 21], Queue = [12, 11, 43, 44]
Enque clicking a stack.
Stack = [], Queue = [12, 11, 43, 44, 21, 22]
Finally, we get
[43, 44, 21, 22, 11, 12]
Note. To determine the block, you may need the peek method in the queue.
Pseudocode Approach 1
void StrangeReverse(Queue<T> q) { Stack<T> s; int count = q.Count(); if (count < 2) return; for (i = 0; i < count; i++) { T elem = q.Deque(); s.Push(elem); } while (s.HasElements()) { T elem = s.Pop(); q.Enque(elem); } // Now the queue has been reversed, // in the normal fashion. ReverseBlocks(q); } void ReverseBlocks(Queue<T> q) { int reversed = 0; int count = q.Count(); while (reversed < count) { reversed += ReverseSingleBlock(q); } } int ReverseSingleBlock(Queue <T> q) { Stack <T> s; T prevElem = q.Deque(); s.Push(prevElem); T curElem = q.Peek(); while(curElem == prevElem) { s.Push(curElem); q.Deque(); prevElem = curElem; curElem = q.Peek(); } int count = 0; while(s.HasElements()) { T elem = s.Pop(); q.Enque(elem); count++; } return count; }