通过一次遍历找到需要反转的子序列前后的两个节点,保存子序列的第一个节点,反转子序列之后将其拼接到原链表中。
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param left int整型 * @param right int整型 * @return ListNode类 */ ListNode* reverseBetween(ListNode* head, int left, int right) { if(left == right) { return head; } int count = 1; ListNode* cur_node = head; ListNode* pre_node = nullptr; ListNode* temp; ListNode* left_node = nullptr; ListNode* right_node = nullptr; ListNode* part_first; while(count <= right) { if(count < left - 1) { cur_node = cur_node->next; } if(count + 1 == left) { left_node = cur_node; cur_node = cur_node->next; } if(count == left) { part_first = cur_node; temp = cur_node->next; cur_node->next = pre_node; pre_node = cur_node; cur_node = temp; } if(count > left && count < right) { temp = cur_node->next; cur_node->next = pre_node; pre_node = cur_node; cur_node = temp; } if(count == right) { if(left_node == nullptr) { head = cur_node; } else { left_node->next = cur_node; } temp = cur_node->next; cur_node->next = pre_node; part_first->next = temp; } count++; } return head; } };