Remove Duplicate from Sorted Linked List in Kotlin

To remove duplicate elements from a sorted linked list, we can traverse the linked list and compare each node’s data with the data of the next node. If the data is the same, we can remove the next node by setting the current node’s next pointer to the next node’s next pointer.

Kotlin
class Node(var data: Int) {
    var next: Node? = null
}

class Node(var data: Int): This class defines a linked list node that contains an integer data value and a reference to the next node in the linked list.

Kotlin
fun removeDuplicates(head: Node?): Node? {
    var curr = head

    while (curr != null && curr.next != null) {
        if (curr.data == curr.next?.data) {
            curr.next = curr.next?.next
        } else {
            curr = curr.next
        }
    }

    return head
}

fun removeDuplicates(head: Node?): Node?: This function takes the head of a sorted linked list as input and removes any duplicate elements from the linked list. It returns the head of the linked list after removing duplicates.

removeDuplicates function works by iterating over the linked list using a curr pointer. At each iteration, it checks if the data value of the current node is the same as the data value of the next node. If they are the same, it removes the next node by setting the next pointer of the current node to the next pointer of the next node. If they are not the same, it moves to the next node in the linked list. The function continues this process until it reaches the end of the linked list.

Kotlin
class Node(var data: Int) {
    var next: Node? = null
}

fun removeDuplicates(head: Node?): Node? {
    var curr = head

    while (curr != null && curr.next != null) {
        if (curr.data == curr.next?.data) {
            curr.next = curr.next?.next
        } else {
            curr = curr.next
        }
    }

    return head
}

fun main() {
    // create a sorted linked list with duplicates
    val head = Node(1)
    head.next = Node(1)
    head.next?.next = Node(2)
    head.next?.next?.next = Node(3)
    head.next?.next?.next?.next = Node(3)

    // print the original linked list
    print("${head.data} ")
    var temp = head.next
    while (temp != null) {
        print("${temp.data} ")
        temp = temp.next
    }
    println()

    // remove duplicates from the linked list
    val newHead = removeDuplicates(head)

    // print the linked list without duplicates
    temp = newHead
    while (temp != null) {
        print("${temp.data} ")
        temp = temp.next
    }
}

fun main(): This function is the entry point of the program. It creates a sorted linked list with duplicates, prints the original linked list, removes duplicates from the linked list using the removeDuplicates function, and prints the linked list without duplicates.

Leave a Comment