k-th element to last of a LinkedList

Implement an algorithm to find the kth to last element of a singly linked list

trait Node {
  def value: Int

  def next: Node
}

object Empty extends Node {
  def value: Int = throw new Error("access empty variable")

  def next: Node = throw new Error("access empty variable")
}

case class NonEmpty(val value: Int, val next: Node = Empty) extends Node

def toLinkedList(lst: List[Int]): Node = {
  if (lst.isEmpty) Empty
  else new NonEmpty(lst.head, toLinkedList(lst.tail))
}

def printLinkedList(head: Node): Unit = head match {
  case Empty =>
  case node: NonEmpty => {
    println(node.value)
    printLinkedList(node.next)
  }
}

/**
  * 2.2
  *
  * @param head
  * @param k
  * @return
  */
def kthElement(head: Node, k: Int): Node = head match {
  case Empty => head
  case node: NonEmpty =>
    if (node.next == Empty) Empty
    else {
      var slow = head
      var fast = head.next
      for (i <- 0 until k - 1 if fast != Empty) {
        fast = fast.next
      }
      while (fast != Empty) {
        slow = slow.next
        fast = fast.next
      }
      slow
    }
}

var node = kthElement(toLinkedList(List(1, 2, 3)), 3)
node.value

Last updated