LeetCode //C - 61. Rotate List

61. Rotate List

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4
Output: [2,0,1]

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 < = k < = 2 ∗ 1 0 9 0 <= k <= 2 * 10^9 0<=k<=2∗109

From: LeetCode

Link: 61. Rotate List


Solution:

Ideas:
  1. Find the Length: First, traverse the list to find its length n.
  2. Calculate Effective Rotation: Since rotating a list of length n places is the same as not rotating it at all, we only need to rotate k mod n places.
  3. Find New Head: Traverse the list to the (n−k mod n)th node. This will be the new tail after rotation.
  4. Perform Rotation: Update the next pointer of the new tail to NULL and set the next pointer of the old tail to the old head.
Code:
c 复制代码
struct ListNode* rotateRight(struct ListNode* head, int k) {
    if (head == NULL || k == 0) {
        return head;
    }
    
    // Step 1: Find the length of the list
    int n = 1;
    struct ListNode *tail = head;
    while (tail->next != NULL) {
        n++;
        tail = tail->next;
    }
    
    // Step 2: Calculate the effective number of rotations needed
    k = k % n;
    if (k == 0) {
        return head;
    }
    
    // Step 3: Find the new head and tail
    struct ListNode *new_tail = head;
    for (int i = 0; i < n - k - 1; i++) {
        new_tail = new_tail->next;
    }
    struct ListNode *new_head = new_tail->next;
    
    // Step 4: Perform the rotation
    new_tail->next = NULL;
    tail->next = head;
    
    return new_head;
}
相关推荐
菜鸟233号20 分钟前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
方便面不加香菜28 分钟前
数据结构--栈和队列
c语言·数据结构
狐5733 分钟前
2026-01-18-LeetCode刷题笔记-1895-最大的幻方
笔记·算法·leetcode
Q741_1471 小时前
C++ 队列 宽度优先搜索 BFS 力扣 662. 二叉树最大宽度 每日一题
c++·算法·leetcode·bfs·宽度优先
Pluchon1 小时前
硅基计划4.0 算法 动态规划进阶
java·数据结构·算法·动态规划
踩坑记录1 小时前
leetcode hot100 54.螺旋矩阵 medium
leetcode
wzf@robotics_notes1 小时前
振动控制提升 3D 打印机器性能
嵌入式硬件·算法·机器人
切糕师学AI2 小时前
ARM 中的 SVC 监管调用(Supervisor Call)
linux·c语言·汇编·arm开发
机器学习之心2 小时前
MATLAB基于多指标定量测定联合PCA、OPLS-DA、FA及熵权TOPSIS模型的等级预测
人工智能·算法·matlab·opls-da
Loo国昌2 小时前
【LangChain1.0】第八阶段:文档处理工程(LangChain篇)
人工智能·后端·算法·语言模型·架构·langchain