反转链表
- 初始化,前节点为空,当前节点为第一个节点,下一个节点根据当前节点是否为空来进行赋值。
- 改变当前节点的下一个节点的指向为前一个节点。
- 前中后节点依次移动。
//链表节点
type ListNode struct {
next *ListNode
data int
}
/*
反转链表:
//初始化
pre为空
cur为第一个节点
for cur不为空 {
next为cur.next
//反转
cur.next变更指向pre
pre变为cur
cur变为next
}
画图更容易理解
*/
func ReverseList(head *ListNode) *ListNode {
var pre *ListNode = nil
cur := head
for cur != nil {
next := cur.next
cur.next = pre
pre = cur
cur = next
}
return pre
}
/*
遍历打印链表
*/
func IteratorList(head *ListNode) {
for head != nil {
fmt.Println(head.data)
head = head.next
}
}
技巧:判断当前节点不为空,才能调用当前节点的下一个节点。在判断的花括号里进行赋值操作。