Skip to content

Instantly share code, notes, and snippets.

@asethia
Created July 30, 2018 19:56
Show Gist options
  • Save asethia/e46f4938109bc72cbdeabd2f56c7c5bb to your computer and use it in GitHub Desktop.
Save asethia/e46f4938109bc72cbdeabd2f56c7c5bb to your computer and use it in GitHub Desktop.
Implement a MyQueue class which implements a queue using two stacks.
/**
* Implement a MyQueue class which implements a queue using two stacks.
* Time Complexity
* Enqueue O(1), DeQueue O(n) if dequeue called after each enqueue
* Space complexity O(n)
* Created by Arun Sethia on 7/30/18.
*/
case class QueueViaStacks(stack: List[Int], queue: List[Int] = Nil) {
def enQueue(elem: Int) = QueueViaStacks(elem :: stack, queue)
def deQueue() = {
queue match {
case Nil if (!stack.isEmpty) => {
val newQueue = stack.foldLeft(List.empty[Int])((a, b) => b :: a)
println(s"dequeue :${newQueue.head}")
QueueViaStacks(Nil, newQueue.tail)
}
case Nil if (stack.isEmpty) => {
throw new UnsupportedOperationException("queue is empty")
}
case h :: _ => {
println(s"dequeue ${h}")
QueueViaStacks(stack, queue.tail)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment