进阶:反转链表2(指定l,r)

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode(int x) : val(x), next(NULL) {}
    7. * };
    8. */
    9. //1. 迭代-----头插法1
    10. class Solution {
    11. public:
    12. ListNode* reverseList(ListNode* head) {
    13. ListNode *prev = nullptr;
    14. ListNode *cur = head;
    15. while(cur){
    16. ListNode *next = cur->next;
    17. cur->next = prev;
    18. prev = cur;
    19. cur = next;
    20. /*
    21. 思路:54321变成12345,后继都变成前驱,所以可以使后继指向自身,之后指针cur后移
    22. */
    23. }
    24. return prev;
    25. }
    26. };
    27. //2. 迭代---就地逆置
    28. class Solution {
    29. public:
    30. ListNode* reverseList(ListNode* head) {
    31. if(!head || !head->next) return head;
    32. auto l = head;
    33. auto r = l->next;
    34. while(r){
    35. auto next = r->next;
    36. r->next = l;
    37. l = r;
    38. r = next;
    39. }
    40. head->next = NULL;
    41. return l;
    42. }
    43. };
    44. //3. 递归
    45. class Solution {
    46. public:
    47. ListNode* reverseList(ListNode* head) {
    48. if(!head || !head->next) return head;
    49. ListNode *cur = reverseList(head->next);
    50. head->next->next = head;
    51. head->next = nullptr;
    52. return cur;
    53. }
    54. };
    55. //4. 迭代,头插法2
    56. class Solution {
    57. public:
    58. ListNode* reverseList(ListNode* head) {
    59. //迭代,头插法
    60. ListNode *dummy = nullptr;
    61. ListNode *cur = head;
    62. while(cur){
    63. ListNode *next = cur->next;
    64. if(!dummy) {
    65. dummy = cur;
    66. dummy->next = NULL;
    67. }else{
    68. cur->next = dummy;
    69. dummy = cur;
    70. }
    71. cur = next;
    72. }
    73. return dummy;
    74. }
    75. };

    递归理解自链接
    image.png