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;
}
相关推荐
文火冰糖的硅基工坊11 分钟前
[人工智能-大模型-103]:模型层 - M个神经元组成的单层神经网络的本质
python·算法·机器学习
无语子yyds38 分钟前
C++双指针算法例题
数据结构·c++·算法
仟濹44 分钟前
「经典数字题」集合 | C/C++
c语言·开发语言·c++
Skrrapper1 小时前
【STL】set、multiset、unordered_set、unordered_multiset 的区别
c++·算法·哈希算法
SunnyKriSmile1 小时前
函数递归求最大值
c语言·算法·函数递归
傻啦嘿哟1 小时前
爬虫数据去重:BloomFilter算法实现指南
爬虫·算法
立志成为大牛的小牛1 小时前
数据结构——三十六、拓扑排序(王道408)
数据结构·学习·程序人生·考研·算法
degen_1 小时前
DXE流程
c语言·笔记·bios
七夜zippoe1 小时前
仓颉FFI实战:C/C++互操作与性能优化
c语言·c++·性能优化
十五学长1 小时前
程序设计C语言
c语言·开发语言·笔记·学习·考研