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

相关推荐
沐欣工作室_lvyiyi2 小时前
IIR数字带通滤波器(论文+源码)
算法·matlab·毕业设计·数字滤波器
tobias.b2 小时前
408真题解析-2010-8-数据结构-拓扑排序
数据结构·算法·计算机考研·408真题解析
txinyu的博客2 小时前
C++ 线程库
开发语言·c++
源代码•宸2 小时前
Golang原理剖析(彻底理解Go语言栈内存/堆内存、Go内存管理)
经验分享·后端·算法·面试·golang·span·mheap
黎子越2 小时前
python循环相关联系
开发语言·python·算法
myloveasuka2 小时前
汉明编码的最小距离、汉明距离
服务器·数据库·笔记·算法·计算机组成原理
沛沛rh452 小时前
Rust浮点数完全指南:从基础到实战避坑
深度学习·算法·计算机视觉·rust
云深处@2 小时前
二叉搜索树
数据结构·c++
安全二次方security²2 小时前
CUDA C++编程指南(7.2)——C++语言扩展之变量内存空间指定符
c++·人工智能·nvidia·cuda·内存空间指定符·__shared__·__device__