题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

定义一个自增索引来确认是否到达要反转的部分,保存要反转的部分的前一个节点left和第一个节点right,在遍历的过程中,到达要反转的部分后,就开始进行反转,到达要反转部分的最后一个节点后,使left指向要反转部分的最后一个节点,right指向下一个节点,返回头节点。如果m的值为1,则left值为nullptr,此时返回要反转部分的最后一个节点。

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* prev = nullptr;
        ListNode* current = head;
        ListNode* node_left;
        ListNode* node_right;
        ListNode* temp;
        int index = 0;
        while (index < n) {
            index++;
            if (index < m) {
                prev = current;
                current = current->next;
            } else if (index == m) {
                node_left = prev;
                node_right = current;
                prev = current;
                current = current->next;
            } else if (index > m) {
                temp = current->next;
                current->next = prev;
                prev = current;
                current = temp;
                if (index == n) {
                    if (m == 1) {
                        node_right->next = current;
                        return prev;
                    } else {
                        node_left->next = prev;
                        node_right->next = current;
                    }
                }
            }
        }
        return head;
    }
};

中等(算法题解) 文章被收录于专栏

中等难度题目

全部评论

相关推荐

炫哥_:哥们项目描述里面vector和mysql之类的都要写吗,直接开头技术栈巴拉巴拉就行了,完全不是技术点啊
点赞 评论 收藏
分享
ResourceUtilization:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务