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;
}
相关推荐
Splendid10 分钟前
Geneformer:基于Transformer的基因表达预测深度学习模型
javascript·算法
愿所愿皆可成24 分钟前
机器学习之聚类Kmeans算法
算法·机器学习·kmeans·聚类
幻奏岚音24 分钟前
统计学(第8版)——假设检验学习笔记(考试用)
笔记·学习·算法
hie9889443 分钟前
基于matlab策略迭代和值迭代法的动态规划
算法·动态规划
Coovally AI模型快速验证1 小时前
SFTrack:面向警务无人机的自适应多目标跟踪算法——突破小尺度高速运动目标的追踪瓶颈
人工智能·神经网络·算法·yolo·计算机视觉·目标跟踪·无人机
Brduino脑机接口技术答疑1 小时前
脑机新手指南(七):OpenBCI_GUI:从环境搭建到数据可视化(上)
人工智能·算法·脑机接口·新手入门
真的很上进1 小时前
2025最全TS手写题之partial/Omit/Pick/Exclude/Readonly/Required
java·前端·vue.js·python·算法·react·html5
linweidong1 小时前
GO 基础语法和数据类型面试题及参考答案(下)
算法·后端面试·泛型·go面试·go面经·go求职
圈圈编码2 小时前
LeetCode Hot100刷题——合并两个有序链表
java·数据结构·算法·leetcode·链表
岁忧2 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 下
sql·leetcode·正则表达式