链表反转
LC 206. Reverse Linked List 反转链表
https://leetcode.com/problems/reverse-linked-list/
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList(head *ListNode) *ListNode { prev := (*ListNode)(nil) for head != nil { next := head.Next head.Next = prev prev = head head = next } return prev }
递归解法
待复习
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList(head *ListNode) *ListNode { if head == nil { return nil } if head.Next == nil { return head } next := head.Next newHead := reverseList(next) next.Next = head head.Next = nil return newHead }