# Dedup LinkedList

FOLLOW UPHow would you solve this problem if a temporary buffer is not allowed

{% tabs %}
{% tab title="Scala" %}

```scala
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(value: Int, next: Node = null) 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.1
  *
  * @param head
  * @return
  */
def deduplicate(head: Node): Node = {
  val dict = scala.collection.mutable.Map[Int, Boolean]()
  def dedup(node: Node): Node = {
    node match {
      case Empty => Empty
      case current: NonEmpty => {
        dict.get(current.value) match {
          case Some(value) => dedup(current.next)
          case None => {
            dict += (current.value -> true)
            new NonEmpty(current.value, dedup(current.next))
          }
        }
      }
    }
  }
  dedup(head)
}

var node = toLinkedList(List(1, 2, 3, 4, 4, 5, 6, 6))
printLinkedList(deduplicate(node))
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/dedup-linkedlist.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
