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;
}
相关推荐
Lugas2 分钟前
为啥说男生找对象尽量在25岁前找到?
算法
MrZhao4004 分钟前
从能跑到可用:一个 Agent Harness 还差哪些工程闭环?
算法
薄情书生13 分钟前
基于51单片机的电子钟设计(LCD12864显示 + DS1302)
c语言·51单片机·protues
QN1幻化引擎35 分钟前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
半条-咸鱼43 分钟前
【FreeRTOS】核心原理与实战速查手册
c语言·操作系统·rtos
白帽小阳1 小时前
Typora插件开发指南:打造专属IDE式写作环境
c语言·网络·python·网络安全·github·pygame·护网行动
学计算机的计算基1 小时前
LeetCode 图论四题精讲:BFS、拓扑排序、Trie 树的模板与优化
java·笔记·算法
浩瀚地学1 小时前
【面试算法笔记】0202-链表-基本功能实现
java·经验分享·笔记·算法·面试
tkevinjd1 小时前
416分割等和子集
java·python·算法·leetcode·职场和发展
Keven_111 小时前
算法札记:Tarjan与拓扑序(Topo)的关系
算法·拓扑·tarjan