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;
}
相关推荐
劲夫学编程28 分钟前
leetcode:杨辉三角
算法·leetcode·职场和发展
毕竟秋山澪31 分钟前
孤岛的总面积(Dfs C#
算法·深度优先
浮生如梦_3 小时前
Halcon基于laws纹理特征的SVM分类
图像处理·人工智能·算法·支持向量机·计算机视觉·分类·视觉检测
励志成为嵌入式工程师4 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
师太,答应老衲吧5 小时前
SQL实战训练之,力扣:2020. 无流量的帐户数(递归)
数据库·sql·leetcode
捕鲸叉5 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer5 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq5 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
wheeldown5 小时前
【数据结构】选择排序
数据结构·算法·排序算法
hikktn7 小时前
如何在 Rust 中实现内存安全:与 C/C++ 的对比分析
c语言·安全·rust