反转链表首先讨论特殊节点,如果节点在首位,则反转之后,首位节点的next值为nil。
func reverse(head *ListNode) *ListNode {
bnode := head//设置默认遍历的前节点,为head
temp := head.Next//从head.next节点开始遍历链表
flage := 0//设置一个标记,用于判断是否为第一个节点
var lnext *ListNode//用于临时保存下一个节点
for temp != nil {//遍历当
lnext = temp.Next//先将遍历节点的下一个节点进行保存
temp.Next = bnode//节点反转,将此节点的next值进行更改,更改为上一个节点
if flage == 0 {//如果是第一个节点,则flage为0
bnode.Next = nil//第一个节点翻转后的next值为nil
flage = 1//将flage值进行更改,避免之后的节点的next值被更改为nil
}
bnode = temp//将节点进行更新,前节点更改为遍历节点
temp = lnext//节点进行更新,由于之前temp.next值已经被更改,但是temp.next值被保存在变量中所以temp = lnext
}
return bnode//返回bnode节点,不能返回temp节点,temp为空,因为temp为空是跳出for循环的标志
}