题解 | 链表内指定区间反转
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstdlib>
#include <iterator>
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
int i = 1;
ListNode *ptr = head; //用于移动的 指针
ListNode *M = nullptr; //标记插入的地方
ListNode *temp; //临时保存
ListNode *change_end;
while (i < m) {
M = ptr;
ptr = ptr->next;
i++;
} // 此时 i=m ptr指向第m个数
change_end = ptr; // 第m个数一定是反转序列的最后一个
if(M != nullptr) { // m!=1
while (i<=n) {
temp = M->next; // 有头指针的头插法
M->next = ptr;
ptr = ptr -> next; i++;
M->next->next = temp;
}
} else{
while (i<=n) { // m=1
temp = ptr; // 没有头指针的头插法
ptr = ptr->next; i++;
if(temp!=head) temp-> next = head; // 第一个的特殊处理
head = temp;
}
}
change_end->next = ptr; // 反转序列的最后一个指向后续顺序序列
return head;
}
};
分成三段考虑额,但是中间需要反转那段需要考虑就多了,因为头插法 和有没有 头指针的操作区别可大喽
查看2道真题和解析