To insert a new node after a given node value in a linked list, you can follow these steps:
- Traverse the linked list until you find the node with the given value.
- Create a new node with the value you want to insert.
- Set the next pointer of the new node to the next pointer of the node you found.
- 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
: aNode
object representing the new node we want to insert into the linked list.
The insertAfter
method works as follows:
- It initializes a variable called
current
to the first node in the linked list (i.e., thehead
property). - 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. - If
current
is not null, the method checks whether the value stored incurrent
is equal to thevalue
argument. If it is, it means we have found the node after which we want to insert the new node. - The
next
property ofnewNode
is set to thenext
property ofcurrent
. - The
next
property ofcurrent
is set tonewNode
, effectively insertingnewNode
into the linked list aftercurrent
.
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.