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

牛群的重新排列

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

        if(left == right) return head;
        
        ListNode* tail = head;
        ListNode* dumpyhead = new ListNode(0);
        dumpyhead->next = head;
        ListNode* start = dumpyhead;

        for(int i = 0; i < right; i++)
        {
            if(left != 1 && i < left - 1)
            {
                start = start->next;
            }
            tail = tail->next;
        }

        ListNode* pre = tail;
        ListNode* cur = start->next;
        while(cur != tail)
        {
            ListNode* tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        start->next = pre;
        return dumpyhead->next;
    }
};

全部评论

相关推荐

秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
SHC2:关键问题是你这三段实习是三个不同的岗位…你这样子秋招就是只有一段实习的本科生..
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务