DSA
Stack and Queue/Implementation

Implement Queue using Stack

class Queue {
  constructor() {
    this.s1 = [];
    this.s2 = [];
  }
 
  push(val) {
    // Step 1: Move all elements from s1 to s2 (reversing order)
    while (this.s1.length) {
      this.s2.push(this.s1.pop());
    }
 
    // Step 2: Add new element to the bottom of s1
    this.s1.push(val);
 
    // Step 3: Move all elements back from s2 to s1 (maintaining queue order)
    while (this.s2.length) {
      this.s1.push(this.s2.pop());
    }
  }
 
  pop() {
    if (this.s1.length === 0) return null;
 
    return this.s1.pop();
  }
 
  peek() {
    if (this.s1.length === 0) return null;
 
    return this.s1[this.s1.length - 1];
  }
}
 
// Time complexity: O(n) for push func and O(1) for others
// Space complexity: O(n)