title: The execution of order or stack and queue: Reversing the First k Elements of a Queue
body: <p><a href="https://i.stack.imgur.com/g8PS6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g8PS6.jpg" alt="enter image description here" /></a></p>
  <p>Hi, this simple problem uses the stack as a helper to reverse elements in a queue.
  Here is the code:</p>
  <pre><code>class CheckReverse {
  
  //1.Push first k elements in queue in a stack.
  //2.Pop Stack elements and enqueue them at the end of queue
  //3.Dequeue queue elements till &quot;k&quot; and append them at the end of queue   
  //4.Dequeue the remaining elements and enqueue them again to append them at end of the queue
  public static &lt;V&gt; void reverseK(Queue&lt;V&gt; queue, int k) {
      if (queue.isEmpty() || k &lt;= 0)
          return;
      Stack&lt;V&gt; stack = new Stack&lt;&gt;(k);
  
      while(!stack.isFull())
          stack.push(queue.dequeue());
  
      while(!stack.isEmpty())
          queue.enqueue(stack.pop());
  
      int size = queue.getCurrentSize();
      for(int i = 0; i &lt; size - k; i++)
          queue.enqueue(queue.dequeue());
  }
  public static void main(String args[]) {
  
      Queue&lt;Integer&gt; queue = new Queue&lt;Integer&gt;(10);
      queue.enqueue(1);
      queue.enqueue(2);
      queue.enqueue(3);
      queue.enqueue(4);
      queue.enqueue(5);
      queue.enqueue(6);
      queue.enqueue(7);
      queue.enqueue(8);
      queue.enqueue(9);
      queue.enqueue(10);
  
      reverseK(queue,5);
  
      System.out.print(&quot;Queue: &quot;);
      while(!queue.isEmpty()) {
        System.out.print(queue.dequeue() + &quot; &quot;);
        }
     }
    }
  </code></pre>
  <p>I got the logic of the answer, but I am just very confused about the order/ sequence for the reverseK method.</p>
  <p>For example,</p>
  <pre><code> while(!stack.isEmpty())
          queue.enqueue(stack.pop());
  </code></pre>
  <p>This is how we pop out all the elements in the temporary stack</p>
  <pre><code>int size = queue.getCurrentSize();
      for(int i = 0; i &lt; size - k; i++){
          queue.enqueue(queue.dequeue());
   }
  </code></pre>
  <p>and this is how we put back all the elements in the queue.</p>
  <p>So are these codes running in the sequence as we wrote them?</p>
  <ol>
  <li><p>why this is queue.dequeue, rather than stack.pop()?
  queue.enqueue(queue.dequeue());</p>
  </li>
  <li><p>since we already have</p>
  <p>queue.enqueue(stack.pop());</p>
  </li>
  </ol>
  <p>why do we still have</p>
  <pre><code>  queue.enqueue(queue.dequeue());
  </code></pre>
  <ol start="3">
  <li>how all these snippets work overall</li>
  </ol>
  <p>Thanks!!</p>