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

相关推荐
皮皮哎哟3 小时前
数据结构:嵌入式常用排序与查找算法精讲
数据结构·算法·排序算法·二分查找·快速排序
程序员清洒3 小时前
CANN模型剪枝:从敏感度感知到硬件稀疏加速的全链路压缩实战
算法·机器学习·剪枝
vortex53 小时前
几种 dump hash 方式对比分析
算法·哈希算法
堕2743 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
初願致夕霞4 小时前
Linux_进程
linux·c++
2302_813806224 小时前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Thera7774 小时前
【Linux C++】彻底解决僵尸进程:waitpid(WNOHANG) 与 SA_NOCLDWAIT
linux·服务器·c++
Wei&Yan4 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
wregjru4 小时前
【QT】4.QWidget控件(2)
c++
浅念-4 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习