链表 - 反转链表

77 阅读1分钟

链表 - 反转链表

这里我们以力扣206题为例,讲讲怎么将链表反转

image.png

具体的流程大家看下面的流程,应该就能知道如何实现了

206.翻转链表.gif 在上图中,我们需要注意一点:[current]节点指向[pre]节点之前,必须将[current.next]保存起来

func reverseList(head *ListNode) *ListNode {
    var pre *ListNode
    current := head
    for current != nil {
        temp := current.Next // 记录当前节点的下一节点
        current.Next = pre
        pre = current
        current = temp
    }
    return pre
}

image.png