leetcode 92 翻转链表II

翻转链表II

高频题(数组转换法)

/**
 * 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* reverseBetween(ListNode* head, int left, int right) {
        ListNode *left_node ;
        vector<int> nums;
        ListNode *rel_head = new ListNode(0,head); 
        ListNode *tmp = rel_head->next;
        bool flag = false;
        int indnx = 1;
        while(tmp != nullptr)
        {
            if(indnx == left) 
            {
                flag = true;
                left_node = tmp;
            }
            if(flag == true) nums.push_back(tmp->val);
            if(indnx == right) break;
            tmp = tmp->next;
            indnx++;
        }
        reverse(nums.begin(),nums.end());
        for(auto it:nums) 
        {
            left_node->val = it;
            left_node = left_node->next;
        }

        return rel_head->next;
    }
};

你可能感兴趣的:(算法刷题,高频题,链表,leetcode,算法)