给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k个位置。
示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]内 -100 <= Node.val <= 1000 <= k <= 2 * 109
答案&测试代码:
cpp
void testLeeCode61(void) {
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) { // LeeCode 61. 旋转链表
if (k == 0 || !head || !head->next) return head;
std::list<ListNode*> list; // 双向链表容器,头部和尾部插入效率高。
for (ListNode* node = head; node; node = node->next) {
list.push_back(node);
}
k %= list.size();
for (int i = 0; i < k; ++i) {
ListNode *last = list.back();
auto it = std::prev(list.end(), 2);
ListNode *pre = *it;
// 断开最后一个节点和前一个节点的链接
pre->next = nullptr;
// 将最后一个节点插入到最前
last->next = head;
head = last;
// list容器也更新
auto tail = std::prev(list.end()); // 尾部迭代器
list.splice(list.begin(), list, tail); // 尾部元素移动到头部
}
return head;
}
};
// test
ListNode node1(1);
ListNode node2(2);
ListNode node3(3);
ListNode node4(4);
ListNode node5(5);
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
node4.next = &node5;
Solution solution;
ListNode *head = solution.rotateRight(&node1, 2);
// 打印:
std:string str = "[";
for (ListNode *node = head; node; node = node->next) {
str += std::to_string(node->val); // 数字转换为字符串再拼接
str += ",";
}
if (str.size() > 1)
str.pop_back();
str += "]";
std::cout << std::format("rotateRight, res: {0}", str) << std::endl;
}
打印:

ok. 提交到LeeCode:

ok. 只是占用内存偏多而已,毕竟使用了一个额外的链表容器。