To reverse a linked list, you can use the following approach:
- Initialize three pointers
prev,curr, andnext. - Traverse the linked list, and for each node, set
nextto the next node,curr.nexttoprev, andprevtocurr. - Continue traversing until
currreaches the end of the linked list (i.e.,currisnull). - Set the
headof the linked list toprev.
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 reverseLinkedList(head: Node?): Node? {
var prev: Node? = null
var curr = head
while (curr != null) {
val next = curr.next
curr.next = prev
prev = curr
curr = next
}
return prev
}reverseLinkedList function takes a head parameter, which is a reference to the head node of a linked list. The function returns a reference to the new head node of the reversed linked list.
The function initializes three pointers: prev, curr, and next. It then traverses the linked list, and for each node, sets next to the next node, curr.next to prev, and prev to curr. This effectively reverses the pointers in the linked list.
The function continues traversing until curr reaches the end of the linked list (i.e., curr is null). It then returns prev, which is the new head node of the reversed linked list.
class Node(var data: Int) {
var next: Node? = null
}
fun reverseLinkedList(head: Node?): Node? {
var prev: Node? = null
var curr = head
while (curr != null) {
val next = curr.next
curr.next = prev
prev = curr
curr = next
}
return prev
}
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)
// print the original linked list
print("${head.data} ")
var temp = head.next
while (temp != null) {
print("${temp.data} ")
temp = temp.next
}
println()
// reverse the linked list
val newHead = reverseLinkedList(head)
// print the reversed linked list
temp = newHead
while (temp != null) {
print("${temp.data} ")
temp = temp.next
}
}In the main function, a linked list is created, and its original contents are printed to the console. The reverseLinkedList function is then called to reverse the linked list, and its new contents are printed to the console.