Insert a Node After a given Node in Kotlin

To insert a new node after a given node value in a linked list, you can follow these steps:

  1. Traverse the linked list until you find the node with the given value.
  2. Create a new node with the value you want to insert.
  3. Set the next pointer of the new node to the next pointer of the node you found.
  4. Set the next pointer of the node you found to the new node.

Here’s an example Kotlin code to insert a new node after a given node value in a linked list:

Kotlin
class Node(var data: Int) {
    var next: Node? = null
}
class LinkedList {
    var head: Node? = null
    fun insertAfter(value: Int, newNode: Node) {
        var current = head

        while (current != null) {
            if (current.data == value) {
                newNode.next = current.next
                current.next = newNode
                return
            }
            current = current.next
        }
        println("Value '$value' not found in linked list")
    }
}
// Example usage
fun main() {
    val ll = LinkedList()
    ll.head = Node(1)
    ll.head!!.next = Node(2)
    ll.head!!.next!!.next = Node(3)

    val newNode = Node(4)
    ll.insertAfter(2, newNode)

    // The linked list should now be 1 -> 2 -> 4 -> 3
}

The Node class represents a single node in the linked list, and has two properties:

  • data: an integer value representing the data stored in the node.
  • next: a reference to the next node in the linked list.

The LinkedList class represents the entire linked list, and has one property:

  • head: a reference to the first node in the linked list.

The LinkedList class also has an insertAfter method, which takes two arguments:

  • value: an integer value representing the value of the node after which we want to insert the new node.
  • newNode: a Node object representing the new node we want to insert into the linked list.

The insertAfter method works as follows:

  1. It initializes a variable called current to the first node in the linked list (i.e., the head property).
  2. It iterates over the linked list by checking whether current is null. If it is, the method exits and prints a message indicating that the value to insert after was not found in the linked list.
  3. If current is not null, the method checks whether the value stored in current is equal to the value argument. If it is, it means we have found the node after which we want to insert the new node.
  4. The next property of newNode is set to the next property of current.
  5. The next property of current is set to newNode, effectively inserting newNode into the linked list after current.

Finally, the main function creates a new linked list, inserts some nodes into it, and then calls the insertAfter method to insert a new node after a specific node.

Leave a Comment