leetcode

206.反转链表

力扣题目链接

206反转链表.png

双指针迭代法

// Definition for singly-linked list.
// struct ListNode {
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
// };
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* current = head;
        ListNode* pre = nullptr;
        while (current){
          // 指针换向
          ListNode* tmp = current->next;
          current->next = pre;
          // 后移
          pre = current;
          current = tmp;
        }
        return pre;
    }
};

递归法

class Solution {
public:
    ListNode* reverse(ListNode* current, ListNode* pre){
        if (!current) return pre; // 错误 return nullptr;
        ListNode*tmp = current->next;
        current->next = pre;
        return reverse(tmp, current);
    }

    ListNode* reverseList(ListNode* head) {
        return reverse(head, nullptr);
    }
};