在想这迭代和递归到底是怎么变换的,必须要理清楚指针。

    迭代写法
    图像理解:
    image.png
    206:

    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. class Solution {
    10. public:
    11. ListNode* reverseList(ListNode* head) {
    12. ListNode* dummy = new ListNode(-1);
    13. dummy->next = head;
    14. ListNode *tail = head;
    15. while(tail && tail->next)
    16. {
    17. ListNode* cur = tail->next;
    18. ListNode* nxt = cur->next;
    19. cur->next = dummy->next;
    20. dummy->next = cur;
    21. tail->next = nxt;
    22. }
    23. return dummy->next;
    24. }
    25. };

    92:

    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. class Solution {
    10. public:
    11. ListNode* reverseBetween(ListNode* head, int m, int n) {
    12. ListNode* dummy = new ListNode(-1);
    13. dummy->next = head;
    14. ListNode* front = dummy;
    15. for(int i = 1; i < m; i++)
    16. front = front->next;
    17. ListNode* tail = front->next;
    18. for(int i = m + 1; i<= n; i++)
    19. {
    20. ListNode* cur = tail->next;
    21. ListNode* nxt = cur->next;
    22. cur->next = front->next;
    23. front->next = cur;
    24. tail->next = nxt;
    25. }
    26. return dummy->next;
    27. }
    28. };

    递归
    图解:
    image.png

    206:

    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. class Solution {
    10. public:
    11. ListNode* reverseList(ListNode* head) {
    12. if(!head || !head->next) return head;
    13. ListNode* p = reverseList(head->next);
    14. head->next->next = head;
    15. head->next = nullptr;
    16. return p;
    17. }
    18. };

    92:

    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. class Solution {
    10. ListNode* tail;
    11. ListNode* dfs(ListNode* head, int cnt)
    12. {
    13. tail = head->next;
    14. if(cnt == 1) return head;
    15. ListNode* p = dfs(head->next, cnt - 1);
    16. head->next->next = head;
    17. head->next = tail;
    18. return p;
    19. }
    20. public:
    21. ListNode* reverseBetween(ListNode* head, int m, int n) {
    22. if(!head) return nullptr;
    23. ListNode* dummy = new ListNode(-1);
    24. dummy->next = head;
    25. ListNode* front = dummy;
    26. for(int i = 1; i < m; i++)
    27. front = front->next;
    28. front->next = dfs(front->next, n - m + 1);
    29. return dummy->next;
    30. }
    31. };