object Main extends App {
  Stream
    .continually(readLine)
    .takeWhile(_ != null)
    .map(_.toInt)
    .foldLeft(Stack.empty[Int]) {
      case (stack, h) =>
        if (h == 0) stack.pop2 match {
          case (e, tail) => println(e); tail
        } else stack.push(h)
    }
}

