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

示例 1:


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

示例 2:


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

提示:
链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

思路:
将k对链表长度(后记为len)取模,如果k与len相等,则k = len,再进行旋转(余数为多少就旋转多少次)。

获取链表长度(帮助函数):

int length(struct ListNode* p) {
    struct ListNode* q = p;
    int length = 0;

    while (q != NULL) {
        length++;
        q = q->next;
    }

    return length;
}

单次旋转:

void rotate(struct ListNode **p) {
    struct ListNode* q = *p;
    struct ListNode *secondToLast = *p;

    while (q != NULL) {
        if (q->next != NULL) {
            secondToLast = q;
        }
        q = q->next;
    }

    secondToLast->next->next = *p;
    *p = secondToLast->next;
    secondToLast->next = NULL;
}
struct ListNode* rotateRight(struct ListNode* head, int k) {
    int len = length(head);
    if (len == 0 || len == 1) return head;
    int _k;
    if (k % len == 0) {
        _k = len;
    }
    else {
        _k = k % len;
    }

    for (int i = 0; i < _k; i++) {
        rotate(&head);
    }

    return head;
}
03-05 22:15