题解 | #牛群旋转#

牛群旋转

https://www.nowcoder.com/practice/5137e606573843e5bf4d8ea0d8ade7f4

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* rotateLeft(ListNode* head, int k) {
        // write code here
        if (head == nullptr) {
            return nullptr;
        }
        int len = 0;
        ListNode* pre = head;
        while (pre) {
            len++;
            pre = pre->next;
        }
        k %= len;
        pre = head;
        for (int i = 0; i < len-k-1; i++) {
            pre = pre->next;
        }
        ListNode* h = pre->next;
        ListNode* p = pre->next;
        pre->next = nullptr;
        while (p->next) {
            p = p->next;
        }
        p->next = head;
        return h;
    }
};

全部评论

相关推荐

牛客383479252号:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务