[LeetCode]Rotate List

链表题again. 实现链表节点的循环移位. 注意k的边界范围。

思路:

1. 得到链表长度N,指针end指向尾节点

2. 找到新链表头节点在老链表中的前驱节点,记为p. p = N-k%N-1

3. end指向原链表head节点,此时链表为环状。更新链表头节点位置,head指向p->next。将p->next置为NULL,成为尾节点。

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

代码

复制代码
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *rotateRight(ListNode *head, int k) {
12         // Note: The Solution object is instantiated only once and is reused by each test case.
13         if(head == NULL || k==0)
14             return head;
15         
16         ListNode *end = head;
17         int N = 1;
18         while(end->next)
19         {
20             ++N;
21             end = end->next;
22         }
23         int p = N-k%N-1;
24         ListNode *pre = head;
25         if(p<0)
26             return head;
27         else
28         {
29             for(int i=0; i<p; ++i)
30                 pre = pre->next;
31             end->next = head;
32             head = pre->next;
33             pre->next = NULL;
34         }
35         return head;
36     }
37 };
复制代码

 

posted @   Apprentice.Z  阅读(136)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
点击右上角即可分享
微信分享提示