Skip to main content

How to reverse a LinkedList in Kotlin

How to reverse a LinkedList in Kotlin.

Here's a step-by-step tutorial on how to reverse a LinkedList in Kotlin:

Step 1: Create the LinkedList class

First, we need to create a class for the LinkedList. This class will have two properties: the head (which points to the first node in the list) and the tail (which points to the last node in the list). We'll also define a function to add nodes to the list.

class LinkedList {
var head: Node? = null
var tail: Node? = null

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

fun addNode(data: Int) {
val newNode = Node(data)
if (head == null) {
head = newNode
tail = newNode
} else {
tail?.next = newNode
tail = newNode
}
}
}

Step 2: Create the reverse function

Next, we'll create a function called reverse that will reverse the LinkedList. This function will iterate through the list and update the next pointers of each node to reverse the order.

fun reverse(list: LinkedList) {
var prev: LinkedList.Node? = null
var current = list.head
var next: LinkedList.Node?

while (current != null) {
next = current.next
current.next = prev
prev = current
current = next
}

list.head = prev
}

Step 3: Test the reverse function

To test the reverse function, we'll create a sample LinkedList, add some nodes, and then call the reverse function. Finally, we'll print the reversed LinkedList to verify the result.

fun main() {
val list = LinkedList()
list.addNode(1)
list.addNode(2)
list.addNode(3)
list.addNode(4)
list.addNode(5)

println("Original LinkedList:")
printLinkedList(list)

reverse(list)

println("Reversed LinkedList:")
printLinkedList(list)
}

fun printLinkedList(list: LinkedList) {
var current = list.head
while (current != null) {
print("${current.data} ")
current = current.next
}
println()
}

When you run the above code, you should see the following output:

Original LinkedList:
1 2 3 4 5
Reversed LinkedList:
5 4 3 2 1

That's it! You have successfully reversed a LinkedList in Kotlin.