Skip to content

Instantly share code, notes, and snippets.

@vkostyukov
Created February 22, 2013 04:46
Show Gist options
  • Save vkostyukov/5010785 to your computer and use it in GitHub Desktop.
Save vkostyukov/5010785 to your computer and use it in GitHub Desktop.
Implementing Stack using two Queues. Push - O(n), Pop - O(1)
import scala.collection.immutable.Queue
class Stack[+A](val in: Queue[A] = Queue.empty[A], val out: Queue[A] = Queue.empty[A]) {
def push[B >: A](v: B): Stack[B] = {
var i = in.enqueue(v)
var o = out
while (!o.isEmpty) {
val (vv, oo) = o.dequeue
o = oo
i = i.enqueue(vv)
}
new Stack(o, i)
}
def pop: (A, Stack[A]) = { val (v, o) = out.dequeue; (v, new Stack(in, o)) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment