course/leetcode/reverseList.go

48 lines
774 B
Go
Raw Normal View History

2024-07-29 00:25:13 +08:00
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
var pre *ListNode
cur := head
for cur != nil {
tmp := cur.Next //暂存初始方向
cur.Next = pre //改变链表方向
pre = cur //移动指针
cur = tmp //移动指针2
}
return pre
}
func main() {
head := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 3,
Next: &ListNode{
Val: 4,
Next: &ListNode{
Val: 5,
Next: nil,
},
},
},
},
}
fmt.Printf("%#v\n", head)
ret := reverseList(head) //反转之后的头节点
fmt.Printf("%#v\n", ret)
for ret != nil {
fmt.Print(ret.Val, "->")
ret = ret.Next //指针移动,直到链表的尾部
}
}