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;
}
相关推荐
算AI4 小时前
人工智能+牙科:临床应用中的几个问题
人工智能·算法
似水এ᭄往昔5 小时前
【C语言】文件操作
c语言·开发语言
hyshhhh6 小时前
【算法岗面试题】深度学习中如何防止过拟合?
网络·人工智能·深度学习·神经网络·算法·计算机视觉
蒙奇D索大6 小时前
【数据结构】第六章启航:图论入门——从零掌握有向图、无向图与简单图
c语言·数据结构·考研·改行学it
杉之7 小时前
选择排序笔记
java·算法·排序算法
烂蜻蜓7 小时前
C 语言中的递归:概念、应用与实例解析
c语言·数据结构·算法
OYangxf7 小时前
图论----拓扑排序
算法·图论
我要昵称干什么7 小时前
基于S函数的simulink仿真
人工智能·算法
AndrewHZ8 小时前
【图像处理基石】什么是tone mapping?
图像处理·人工智能·算法·计算机视觉·hdr
念九_ysl8 小时前
基数排序算法解析与TypeScript实现
前端·算法·typescript·排序算法