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. 只是占用内存偏多而已,毕竟使用了一个额外的链表容器。

相关推荐
phltxy6 小时前
C语言操作符详解
java·c语言·算法
RuoZoe6 小时前
从 2026 年 3 月 1 日开源,到 26.10.9:Jalium UI 半年时间到底走了多远?
c语言·c++
aqiu1111116 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye7 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考7 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
鱼子星_7 小时前
【C++】继承和多态(上)
c++·笔记
玖玥拾8 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研9 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
郝学胜-神的一滴9 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生