题解 | #牛群的重新排列#

牛群的重新排列

https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838

通过一次遍历找到需要反转的子序列前后的两个节点,保存子序列的第一个节点,反转子序列之后将其拼接到原链表中。

/**
 * 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;
    }
};

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

中等难度题目

全部评论

相关推荐

点赞 评论 收藏
分享
10-13 16:58
门头沟学院 Java
面了100年面试不知...:一周七天,一天去一家上班😍😍😍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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