题目: https://leetcode-cn.com/problems/reverse-linked-list/
多指针
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
// next := head.Next
// head.Next = prev
// prev = head
// head = next
head.Next, prev, head = prev, head, head.Next
}
return prev
}
递归YYDS
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
curr := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return curr
}