LeeCode 61. 旋转链表

给你一个链表的头节点 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 <= 100
  • 0 <= 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. 只是占用内存偏多而已,毕竟使用了一个额外的链表容器。

相关推荐
释厄62333 分钟前
多黑洞具现论·物理/生物/金融三域显化·虚拟宇宙黑洞·奇点=0 圆圈
开发语言·数据结构·人工智能·程序人生·安全威胁分析
UIU1142 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
Fruit_Caller2 小时前
static
开发语言·c++
用户979984807187 小时前
200 行代码写一个能跑的 AI Agent:不依赖任何框架,只靠 tool-calling 原理
算法
threerocks7 小时前
【Muse实战】X 流量作战室搭建保姆级教程 - 拥有你自己的运营团队
算法
GreenTea7 小时前
深度拆解 ScienceBuddy:如何用“双层递归自进化”构建高可靠科研 Agent Harness
前端·后端·算法
花椒技术7 小时前
2.46 秒生成 5 秒视频:拆解 H3 Max 的模型、推理栈与硬件协同
算法·音视频开发·视频编码
vivo互联网技术7 小时前
ART:妆容迁移框架,重新定义高保真妆容迁移 | ECCV 2026
人工智能·算法·图像识别
用户0441440924497 小时前
卫星信号模拟器里的四个坐标转换公式
算法
橘和柠7 小时前
阿里 open-code-review (AI代码审查工具)实战:安装、四层规则链、自定义规则格式与实测避坑
算法·面试