题目链接
    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    示例1:

    1. 输入:head = [1,2,3,4,5]
    2. 输出:[5,4,3,2,1]

    示例2:

    1. 输入:head = [1,2]
    2. 输出:[2,1]

    示例3:

    1. 输入:head = []
    2. 输出:[]

    提示:

    • 链表中节点的数目范围是 [0, 5000]
    • -5000 <= Node.val <= 5000
    1. 双指针

      1. /**
      2. * Definition for singly-linked list.
      3. * public class ListNode {
      4. * int val;
      5. * ListNode next;
      6. * ListNode() {}
      7. * ListNode(int val) { this.val = val; }
      8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      9. * }
      10. */
      11. class Solution {
      12. public ListNode reverseList(ListNode head) {
      13. ListNode pre = null;
      14. ListNode current = head;
      15. ListNode temp = null;
      16. while (current != null){
      17. temp = current.next;
      18. current.next = pre;
      19. pre = current;
      20. current = temp;
      21. }
      22. return pre;
      23. }
      24. }
    2. 递归

      /**
      * Definition for singly-linked list.
      * public class ListNode {
      *     int val;
      *     ListNode next;
      *     ListNode() {}
      *     ListNode(int val) { this.val = val; }
      *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      * }
      */
      class Solution {
       public ListNode reverseList(ListNode head) {
           return reverse(null, head);
       }
       public ListNode reverse(ListNode prev, ListNode cur) {
           // 递归终止条件,在当前指向null时
           // 空链表 head=null 或者是 已经翻转完最后一个元素
           if(cur == null) {
               return prev;
           }
           ListNode temp = cur.next; //保存下一个节点
           cur.next = prev; // 翻转当前节点
           return reverse(cur, temp); // 相当于双指针的 pre = current; current = temp;
       }
      }