Skip to content

Instantly share code, notes, and snippets.

@pavithranrao
Forked from pathikrit/Node.scala
Created February 17, 2018 23:36
Show Gist options
  • Save pavithranrao/5f8020ca511a97b92686354d1e5318b5 to your computer and use it in GitHub Desktop.
Save pavithranrao/5f8020ca511a97b92686354d1e5318b5 to your computer and use it in GitHub Desktop.
Reverse a LinkedList in Scala
case class Node(value: Int, next: Option[Node])
def reverse(node: Node, prev: Option[Node] = None): Node = {
val reversed = node.copy(next = prev)
node.next map {reverse(_, Some(reversed))} getOrElse reversed
}
/****************************************************************/
val one = Node(1,Some(Node(2,Some(Node(3,None)))))
println(s"$one\n${reverse(one)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment