跳转至

61. 旋转链表

难度:中等

题目

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

Example

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

Example

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

  • 链表中节点的数目在范围 [0, 500]
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

Reference

题解

先将链表闭环,右移 k 个节点后以该节点作为头节点,将链表的环打开。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* rotateRight(struct ListNode* head, int k) {
    if (!head)
        return NULL;
    struct ListNode *cur = head, *ret = NULL;
    int len = 1;
    while (cur->next != NULL)
    {
        cur = cur->next;
        len++;
    }
    cur->next = head;
    cur = head;
    k %= len;
    for (int i = k + 1; i < len; i++)
        cur = cur->next;
    ret = cur->next;
    cur->next = NULL;
    return ret;
}

评论