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;
}
相关推荐
普通攻击往后拉9 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
Nebula嵌入式9 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
@syh.9 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发10 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕10 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI10 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
天空'之城11 小时前
C 语言工业级通用组件手写 23:卡尔曼滤波(简易版)
c语言·卡尔曼滤波·嵌入式算法·工业级组件
Angel Q.11 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
888CC++12 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++