题解 | #牛群旋转# 循环链表应用题

牛群旋转

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

知识点

链表

题意分析

链表循环右移k位,链表长度为n,那么右移k次和右移k%n次的效果相同。

因此虽然k的范围很大,但是取模之后 k % n<n

相当于把链表的后k%n个元素移到链表的头部,这里实现上可以用两个指针,一个先移动k%n次,然后两个一起移动,当前面的移动到了末尾,前面的指针就到了倒数第k%n的位置,从这里接到链表头部即可。

时间复杂度

只需要遍历链表若干次,时间复杂度O(n)

AC code (C++)

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

全部评论

相关推荐

09-13 17:25
亲切的00后在笔试:我也遇到了,所以我早他一步查看图片
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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