难度:简单 题目来源:力扣(LeetCode) https://leetcode-cn.com/problems/reverse-linked-list

    说明:
    反转一个单链表。

    示例:_

    输入:1->2->3->4->5->NULL 输出:5->4->3->2->1->NULL

    解法:
    常规遍历

    1. /**
    2. * Definition for singly-linked list.
    3. * type ListNode struct {
    4. * Val int
    5. * Next *ListNode
    6. * }
    7. */
    8. func reverseList(head *ListNode) *ListNode {
    9. var tmp *ListNode
    10. for head != nil {
    11. tmp = &ListNode{Val: head.Val, Next: tmp}
    12. head = head.Next
    13. }
    14. return tmp
    15. }


    递归**

    1. /**
    2. * Definition for singly-linked list.
    3. * type ListNode struct {
    4. * Val int
    5. * Next *ListNode
    6. * }
    7. */
    8. func reverseList(head *ListNode) *ListNode {
    9. if head == nil || head.Next == nil {
    10. return head
    11. }
    12. last := reverseList(head.Next)
    13. head.Next.Next = head
    14. head.Next = nil
    15. return last
    16. }