当前位置:网站首页>LeetCode-61
LeetCode-61
2022-07-05 06:16:00 【GreedySnaker】
Give you a list of the head node head , Rotate the list , Move each node of the list to the right k A place .
At first, I thought about finding a new head according to the number of moves , New tail , Direct link . Later, we found that the circular linked list can record the node precursor and follower with fewer variables .
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k)
{
// Does not meet the conditions or there is only one node
if (head == NULL || head->next == NULL || k == 0)
{
return head;
}
// Record the number of linked list elements , Find the tail node
ListNode* temp = head;
int num = 1;
while (temp->next != NULL)
{
temp = temp->next;
num++;
}
//k When it is greater than the number of elements , Just deal with the remainder
k = k % num;
if (k == 0)
{
return head;
}
// Connect the single linked list into a circular list
temp->next = head;
// According to the number of shifts to the right , Cut off the ring linked list at the corresponding position , Return to new header
temp = head;
for (int i = 1; i < (num - k); i++)
{
temp = temp->next;
}
ListNode* res = temp->next;
// Segmented ring linked list
temp->next = NULL;
return res;
}
};
边栏推荐
猜你喜欢
MIT-6874-Deep Learning in the Life Sciences Week 7
Simple selection sort of selection sort
1.13 - RISC/CISC
LeetCode 0107.二叉树的层序遍历II - 另一种方法
数据可视化图表总结(一)
Data visualization chart summary (I)
Error ora-28547 or ora-03135 when Navicat connects to Oracle Database
可变电阻器概述——结构、工作和不同应用
4. 对象映射 - Mapping.Mapster
Overview of variable resistors - structure, operation and different applications
随机推荐
打印机脱机时一种容易被忽略的原因
[rust notes] 16 input and output (Part 2)
传统数据库逐渐“难适应”,云原生数据库脱颖而出
数据可视化图表总结(二)
leetcode-6111:螺旋矩阵 IV
Daily question 2006 Number of pairs whose absolute value of difference is k
可变电阻器概述——结构、工作和不同应用
[rust notes] 17 concurrent (Part 1)
Simple selection sort of selection sort
MySQL advanced part 2: the use of indexes
4. 对象映射 - Mapping.Mapster
leetcode-9:回文数
多屏电脑截屏会把多屏连着截下来,而不是只截当前屏
SQLMAP使用教程(二)实战技巧一
Real time clock (RTC)
SPI details
[rust notes] 15 string and text (Part 1)
Doing SQL performance optimization is really eye-catching
Regulations for network security events of vocational group in 2022 Guizhou Vocational College skill competition
Leetcode backtracking method