题目链接
    image.png

    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. /**
    12. 每次递归都会得到的数据有
    13. head表示的是当前的节点
    14. 可以有:head head.next
    15. 需要做的是将head.next.next = head;从最后面开始做起
    16. */
    17. class Solution {
    18. // 递归
    19. public ListNode reverseList(ListNode head) {
    20. if(head == null || head.next == null) return head;
    21. ListNode newHead = reverseList(head.next); // 保存的永远是最后一个节点
    22. head.next.next = head;
    23. head.next = null;
    24. return newHead;
    25. }
    26. // 迭代
    27. public ListNode reverseList1(ListNode head) {
    28. if(head == null || head.next == null) return head;
    29. ListNode prev = null,cur;
    30. cur = head;
    31. while(cur != null) {
    32. ListNode tmp = cur.next;
    33. cur.next = prev;
    34. prev = cur;
    35. cur = tmp;
    36. }
    37. return prev;
    38. }
    39. }