loicdescotte
4/22/2015 - 12:17 AM

Reverse a LinkedList in Scala

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)}")