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

相关推荐
2301_819414301 天前
C++与区块链智能合约
开发语言·c++·算法
Zaly.1 天前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
不想看见4041 天前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
老约家的可汗1 天前
C/C++内存管理探秘:从内存分布到new/delete的底层原理
c语言·c++
做怪小疯子1 天前
蚂蚁暑期 319 笔试
算法·职场和发展
天赐学c语言1 天前
Linux - 应用层自定义协议与序列/反序列化
linux·服务器·网络·c++
计算机安禾1 天前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
啊哦呃咦唔鱼1 天前
LeetCode hot100-73 矩阵置零
算法
阿贵---1 天前
C++构建缓存加速
开发语言·c++·算法
波特率1152001 天前
C++当中is-a(继承)与has-a(成员对象)的辨析与使用指南(包含实际工程当中的使用示例)
c++·ros·串口通信