题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <bits/types/struct_tm.h>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
ListNode* list_head = head;
// find right pos
ListNode* start_node = nullptr;
ListNode* right_node = head;
ListNode* cursor_node = head;
int size = 0;
// find right_node and claim start_node if pos not equals 1
for (int i = 1; i <= n; i++, size++) {
if (cursor_node == nullptr) {
break;
}
if (i == n) {
right_node = cursor_node;
}
if (m > 1 && i == m - 1) {
start_node = cursor_node;
}
cursor_node = cursor_node->next;
}
// special condition: m equals 1, construct an empty node as head node
if (nullptr == start_node && m == 1) {
start_node = new ListNode(2000);
start_node->next = head;
}
// save temp start_node->next
ListNode* tmp_node = start_node->next;
// start_node->next point to right_node
start_node->next = right_node;
// then tail insert
while (tmp_node != right_node) {
ListNode* tmp_next_node = tmp_node->next;
tmp_node->next = right_node->next;
right_node->next = tmp_node;
tmp_node = tmp_next_node;
}
// special condition
if (m == 1) {
list_head = start_node->next;
} else {
list_head = head;
}
return list_head;
}
};
