反转一个单链表。
    示例:
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
    法一:迭代

    • 时间复杂度:O(n),假设 n是列表的长度,时间复杂度是 O(n)。
    • 空间复杂度:O(1)。
    • 最主要还是有个pre,cur,tmp,然后迭代。
      1. class Solution {
      2. public ListNode reverseList(ListNode head) {
      3. ListNode pre = null;
      4. ListNode cur = head;
      5. while (cur != null) {
      6. ListNode temp = cur.next;
      7. cur.next = pre;
      8. pre = cur;
      9. cur = temp;
      10. }
      11. return pre;
      12. }
      13. }
      206. 反转链表 - 图1
      法二:递归,有点难理解,背答案吧
      假设链表是[1, 2, 3, 4, 5]从最底层最后一个reverseList(5)来看
    1. 返回了5这个节点
    2. reverseList(4)中
    3. p为5
    4. head.next.next = head 相当于 5 -> 4
    5. 现在节点情况为 4 -> 5 -> 4
    6. head.next = null,切断4 -> 5 这一条,现在只有 5 -> 4
    7. 返回(return)p为5,5 -> 4
    8. 返回上一层reverseList(3)
    9. 处理完后返回的是4 -> 3
    10. 依次向上
      1. class Solution {
      2. public ListNode reverseList(ListNode head) {
      3. if(head == null || head.next == null) return head;
      4. ListNode p = reverseList(head.next);
      5. head.next.next = head;
      6. head.next = null;
      7. return p;
      8. }
      9. }
      206. 反转链表 - 图2