reverse_linked_list
reverse_linked_list.go 源码
package main
//反转链表
//迭代
func reverseList1(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
head.Next, prev, head = prev, head, head.Next
}
return prev
}
//递归
func reverseList(head *ListNode) *ListNode {
return helper(nil, head)
}
func helper(prev, cur *ListNode) *ListNode {
if cur == nil {
return prev
}
next := cur.Next
cur.Next = prev
return helper(cur, next)
}
//官方的递归解法
func reverseList2(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
p := reverseList2(head.Next)
head.Next.Next = head
head.Next = nil
return p
}
你可能感兴趣的文章
0
赞
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦