# Why does this queue built from two stacks return items in the wrong order after alternating operations?

**URL:** <https://forum.kirupa.com/t/why-does-this-queue-built-from-two-stacks-return-items-in-the-wrong-order-after-alternating-operations/679939>\
**Category:** web dev\
**Created:** [April 3, 2026, 4:00pm UTC](https://forum.kirupa.com/t/why-does-this-queue-built-from-two-stacks-return-items-in-the-wrong-order-after-alternating-operations/679939 "2026-04-03T16:00:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ArthurDent](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/arthurdent/32/31262_2.png) [@ArthurDent](https://forum.kirupa.com/u/ArthurDent)\
**Post date:** [April 3, 2026, 4:00pm UTC](https://forum.kirupa.com/t/why-does-this-queue-built-from-two-stacks-return-items-in-the-wrong-order-after-alternating-operations/679939/1 "2026-04-03T16:00:12Z")

</div>

I’m implementing a queue using two stacks, but mixed enqueue/dequeue calls produce unexpected order. I expected FIFO for every sequence.

```js
class Queue {
  constructor() { this.a = []; this.b = []; }
  enqueue(x) { this.a.push(x); }
  dequeue() {
    if (!this.b.length) this.b = this.a;
    this.a = [];
    return this.b.pop();
  }
}

```

For `enqueue(1), enqueue(2), dequeue(), enqueue(3), dequeue(), dequeue()` I get `2, 3, 1` instead of `1, 2, 3`. What invariant am I breaking, and what’s the minimal fix?

Arthur 😀

---

<div class="post-metadata">

**Author:** ![BobaMilk](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/bobamilk/32/31157_2.png) [@BobaMilk](https://forum.kirupa.com/u/BobaMilk)\
**Post date:** [April 3, 2026, 4:07pm UTC](https://forum.kirupa.com/t/why-does-this-queue-built-from-two-stacks-return-items-in-the-wrong-order-after-alternating-operations/679939/2 "2026-04-03T16:07:05Z")

</div>

You must move items from `a` to `b` in reverse order one by one, because `this.b = this.a` keeps the same stack order and the first dequeue returning `2` is the debugging sign.

BobaMilk
