Reverse a linked list

  • + 0 comments

    Scala, with recursion:

         def reverse(llist: SinglyLinkedListNode): SinglyLinkedListNode = {
          @tailrec
          def reverseNode(node: SinglyLinkedListNode, next: SinglyLinkedListNode): SinglyLinkedListNode = {
            if (node == null) next
            else {
              val prev = node.next
              node.next = next
              reverseNode(prev, node)
            }
          }
          reverseNode(llist, null)
        }