题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <endian.h>
#include <functional>
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
if (m == n)
return head; // 如果 m 等于 n,无需反转,直接返回原链表
auto dummy = new ListNode(-1); // 创建一个哑节点,作为反转部分的起点的前一个节点
dummy->next = head; // 将哑节点指向原链表的头节点
ListNode* pre = dummy; // pre 用于记录反转部分起点的前一个节点
ListNode* cur = head; // cur 用于遍历链表,初始指向头节点
ListNode* nex = nullptr; // nex 用于记录当前节点的下一个节点
// 找到第 m-1 个节点,即反转部分起点的前一个节点
for (int i = 0; i < m - 1; i++) {
pre = cur;
cur = cur->next;
}
// 反转从第 m 个到第 n 个节点
ListNode* then = cur->next; // then 记录反转区间第一个节点的下一个节点,即第二个节点
for (int i = 0; i < n - m; i++) { // 只需要反转 n-m 次
cur->next = then->next; // 将当前节点的 next 指向下一个要处理的节点的 next
then->next = pre->next; // 将要反转的节点的 next 指向反转部分起点的前一个节点的 next
pre->next = then; // 将反转部分起点的前一个节点的 next 指向当前要反转的节点
then = cur->next; // 更新 then 为下一个要处理的节点
}
return dummy->next; // 返回哑节点的 next,即反转后的链表头节点
}
};
数据结构练习 文章被收录于专栏
数据结构练习
查看3道真题和解析