Created
July 30, 2018 19:56
-
-
Save asethia/e46f4938109bc72cbdeabd2f56c7c5bb to your computer and use it in GitHub Desktop.
Implement a MyQueue class which implements a queue using two stacks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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