题解 | #牛群旋转#

牛群旋转

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

每一次将链表最后一个节点移到首位,重复k次,就可得到预期的结果。

/**
 * 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 || head->next == nullptr) {
            return head;
        }
        ListNode* cur_node = head->next;
        ListNode* pre_node = head;
        for(int i = 0; i < k; i++) {
            while(cur_node != nullptr) {
                if(cur_node->next == nullptr) {
                    cur_node->next = head;
                    pre_node->next = nullptr;
                    head = cur_node;
                    break;
                }
                pre_node = cur_node;
                cur_node = cur_node->next;
            }
            cur_node = head->next;
            pre_node = head;
        }
        return head;
    }
};

较难(算法题解) 文章被收录于专栏

较难难度题目

全部评论

相关推荐

Sigma429:极兔啊,薪资开的巨低,还在上海,索性不做笔试了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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