Skip to content

Instantly share code, notes, and snippets.

@gcnyin
Last active January 11, 2022 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcnyin/f45c96a3b68467998c6784f332884ff5 to your computer and use it in GitHub Desktop.
Save gcnyin/f45c96a3b68467998c6784f332884ff5 to your computer and use it in GitHub Desktop.
reverse linkedlist
import scala.annotation.tailrec
object Main extends App {
sealed trait Node
case class Branch(value: Int, next: Node) extends Node
case class Leaf(value: Int) extends Node
def reverse: Node => Node = {
case Branch(value, next) => _reverse(Leaf(value), next)
case l @ Leaf(_) => l
}
@tailrec
def _reverse(n1: Node, n2: Node): Node = {
n2 match {
case Branch(v1, next) =>
_reverse(Branch(v1, n1), next)
case Leaf(value) =>
Branch(value, n1)
}
}
println(reverse(Branch(1, Branch(2, Branch(3, Leaf(4))))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment