leetcode 92 反转链表 Ⅱ

58 阅读1分钟

第一次 一次通过中等题!

/**
 * 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:
    vector<ListNode*> reverseList(ListNode* head) {
        vector<ListNode*> result;
        result.push_back(head);
        ListNode* prev = nullptr;
        ListNode* curr = head;
        ListNode* next = nullptr;
        while(curr) {
            next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        result.push_back(prev);
        return result;
    }
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* prev = dummy;
        ListNode* curr = head;
        for(int i = 0; i < left - 1; i++) {
            curr = curr->next;
            prev = prev->next;
        }
        ListNode* next = curr;
        for(int i = 0; i < right -left; i++) {
            next = next->next;
        }
        ListNode* tmp = next;
        next = next->next;
        tmp->next = nullptr;
        vector<ListNode*> result = reverseList(curr);
        result[0]->next = next;
        prev->next = result[1];
        return dummy->next;
    }
};

其实就是在反转链表的基础上进行一些扩展,ac之后查看官方题解,发现自己的代码存在可优化的地方:reverseList函数不需要返回值,因为在遍历时已经保存反转链表的前后指针 可进行优化

有时间再改