Created
February 22, 2013 04:46
-
-
Save vkostyukov/5010785 to your computer and use it in GitHub Desktop.
Implementing Stack using two Queues. Push - O(n), Pop - O(1)
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
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