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

牛群的重新排列

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) {
        // write code here
        int count = 0;
        if(!head || !head->next)
            return head;
        ListNode *pstart;
        ListNode *pend;
        ListNode *prestart = nullptr;
        ListNode *nextend = nullptr;
        auto cur = head;
        ListNode* pre = nullptr;
        while(cur!=nullptr){
            count ++;
            if(count == left){
                pstart = cur;
                prestart = pre;
            }
            if(count == right){
                pend = cur;
                break;
            }
            pre = cur;
            cur = cur->next;
        }
        if(!pstart || !pend){
            return head;
        }
        nextend = pend->next;
        if(prestart){
            prestart->next = nullptr;
        }
        pend->next = nullptr;
        cur = pstart;
        pre = nullptr;
        while(cur!=nullptr){
            auto next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        if(prestart)
            prestart->next = pre;
        pstart->next = nextend;
        return (head == pstart)? pend: head;
    }
};

全部评论

相关推荐

10-07 23:57
已编辑
电子科技大学 Java
八街九陌:博士?客户端?开发?啊?
点赞 评论 收藏
分享
冷艳的小师弟在看机会:jd测评乱点直接被挂了,哭死~
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务