Skip to main content
3 of 3
deleted 3 characters in body

Queue implemented using two stacks in Swift

I need your expert opinion! In fact, for a Leetcode Problem, I had to code a queue using 2 stacks. It's shown just below and functions well.

It is a pretty simple code with peek, pop, push, etc. functions, quite classic. But this code does not please me completely since I coalesce the optionals with a default value, taken out of my hat, to avoid forced unwrapping.

Do you see a more professional way to write this?

class MyQueue {

private var stack1: [Int]
private var stack2: [Int]
private var front: Int?

init() {
  stack1 = []
  stack2 = []
}

func push(_ x: Int) {
  if stack1.isEmpty {
    front = x
  }
  stack1.append(x)
}

func pop() -> Int {
  if stack2.isEmpty {
    while !stack1.isEmpty {
      stack2.append(stack1.popLast() ?? -1)
    }
  }
  return stack2.popLast() ?? -1
}

func peek() -> Int {
  if !stack2.isEmpty {
    return stack2.last ?? -1
  }

  return front ?? -1
}

func empty() -> Bool {
  return stack1.isEmpty && stack2.isEmpty
    }
}