旋转链表

in 知识共享 with 0 comment

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

示例 1:
rotate1.jpg

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

示例 2:
roate2.jpg

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

提示:

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

本人提交代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        ListNode* p = head;
        if ( !p || !p->next )
            return p;

        int len = 1;
        while ( p->next )
        {
            p = p->next;
            len++;
        }

        p->next = head;
        k = k % len;

        for ( int i = 0; i < len - k; i++ )
            p = p->next;

        head = p->next;
        p->next = NULL;

        return head;
    }
};
Responses