[Leetcode]0206.Reverse Linked List

55 阅读1分钟

Description:
    Given the head of a singly linked list, reverse the list, and return the reversed list.

image.png

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Solutions:
    If we want to reverse the list, we need at least three points to represent the current, front and tail positions. Otherwise, after the current will reverse its direction and point to the tail, the Linked list will be broken since the current point can not move to next one.
<-口(tail)<-口(current)   口->口->
    We may initialize the tail as null, so that when the head note reverses direction, it easily point to the null without requiring any further operations. Then, by making front point to the next node, we can simply discover the next node following the current node that points to the tail. Third, let the current node refer to the tail. Finally, we allocate the tail to the current and the current to the front. So we can repeat this method till the current is null. At the same time, the tail will function as the head of the inverted linked list. That is what we need.
<-口(tail)  口(current)->口->口->
<-口(tail)  口(current)->口(front)->口->
<-口(tail)<-口(current)   口(front)->口->
<-口<-口(tail)   口(current,front)->口->

fun reverseList(head: ListNode?): ListNode? {
    // or you may construct a null tail which need to judge head.
    var tail: ListNode? = null  
    var current = head
    while(current != null) {
        val temp = current.next
        current.next = tail
        tail = current
        current = temp
    }
    return tail
}