[LeetCode] Rotate List

Well, in the case of a linked list instead of an array, the problem becomes easier. We just need to find the node that will be the new head of the list after the rotation and then restructure the list.

复制代码
 1 class Solution {
 2 public:
 3     ListNode* rotateRight(ListNode* head, int k) {
 4         if (!head) return NULL;
 5         int len = listLength(head);
 6         k %= len;
 7         ListNode* fast = head;
 8         for (int i = 0; i < k; i++)
 9             fast = fast -> next;
10         ListNode* slow = head;
11         while (fast -> next) {
12             slow = slow -> next;
13             fast = fast -> next;
14         }
15         fast -> next = head;
16         head = slow -> next;
17         slow -> next = NULL;
18         return head;
19     }
20 private:
21     int listLength(ListNode* head) {
22         int len = 0;
23         while (head) {
24             len++;
25             head = head -> next;
26         }
27         return len;
28     }
29 };
复制代码

 

posted @   jianchao-li  阅读(167)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一文搞懂MCP协议与Function Call的区别
· 一次Java后端服务间歇性响应慢的问题排查记录
点击右上角即可分享
微信分享提示