题解 | #牛群旋转#
牛群旋转
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; } };
较难(算法题解) 文章被收录于专栏
较难难度题目