To find the middle element of a linked list, you can use the slow and fast pointer approach. Here are the steps:
- Initialize two pointers,
slow_ptr
andfast_ptr
, to the head of the linked list. - Move
fast_ptr
two nodes at a time andslow_ptr
one node at a time untilfast_ptr
reaches the end of the linked list. - The node at which
slow_ptr
is pointing to is the middle element of the linked list.
class Node(var data: Int) {
var next: Node? = null
}
Node
class represents a node in the linked list, with an integer data
and a next
reference to the next node in the list.
fun findMiddleElement(head: Node?): Int? {
var slowPtr = head
var fastPtr = head
while (fastPtr != null && fastPtr.next != null) {
slowPtr = slowPtr?.next
fastPtr = fastPtr.next?.next
}
return slowPtr?.data
}
The findMiddleElement
function takes a head
parameter, which is a reference to the head node of a linked list. The function returns the value of the middle element of the linked list, or null
if the list is empty.
The function uses the slow and fast pointer approach to find the middle element. The slowPtr
and fastPtr
variables are initialized to the head
node of the linked list.
The function then enters a loop, where the fastPtr
variable moves ahead two nodes at a time, while the slowPtr
variable moves ahead one node at a time. This continues until the fastPtr
variable reaches the end of the list (i.e., its next
reference is null
), or the second-to-last node (i.e., its next
reference is null
but its next.next
reference is not null
).
At this point, the slowPtr
variable is pointing to the middle element of the list, since it has moved halfway through the list while the fastPtr
variable has moved all the way to the end (or close to the end). The function returns the value of the slowPtr
node’s data
field, which is the value of the middle element.
If the linked list is empty (i.e., the head
parameter is null
), then the function returns null
, indicating that there is no middle element to be found.
class Node(var data: Int) {
var next: Node? = null
}
fun findMiddleElement(head: Node?): Int? {
var slowPtr = head
var fastPtr = head
while (fastPtr != null && fastPtr.next != null) {
slowPtr = slowPtr?.next
fastPtr = fastPtr.next?.next
}
return slowPtr?.data
}
fun main() {
// create a linked list
val head = Node(1)
head.next = Node(2)
head.next?.next = Node(3)
head.next?.next?.next = Node(4)
head.next?.next?.next?.next = Node(5)
// find the middle element
val middleElement = findMiddleElement(head)
// print the middle element
if (middleElement != null) {
println("The middle element is $middleElement")
} else {
println("The linked list is empty")
}
}
In the main
function, a linked list is created and the findMiddleElement
function is called to find the middle element. The value of the middle element is printed to the console.