Skip to content

Instantly share code, notes, and snippets.

@pathikrit
Last active September 17, 2021 02:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pathikrit/4af1c1c2c590c2478b0f to your computer and use it in GitHub Desktop.
Save pathikrit/4af1c1c2c590c2478b0f 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)}")
@pathikrit
Copy link
Author

@nsfyn55: This was a interview question where each node was presented in Java as:

public class Node(int value, Node next) {}

@v66moroz: Yes, ADTs make more sense here but this was presented in an interview with above Java class as example. I adapted it to Scala.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment