Last active
January 11, 2022 09:34
-
-
Save gcnyin/f45c96a3b68467998c6784f332884ff5 to your computer and use it in GitHub Desktop.
reverse linkedlist
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.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