0
点赞
收藏
分享

微信扫一扫

Leecode 61. 旋转链表

陬者 2022-04-27 阅读 78

原题链接:Leecode 61. 旋转链表
在这里插入图片描述
在这里插入图片描述

/**
 * 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) {
        if(head==nullptr) return nullptr;
        if(!k) return head;
        ListNode* root=head;
        ListNode* pre=head;
        int num=1;
        while(head->next)
        {
            num++;
            pre=head;
            head=head->next;
        }
        k%=num;
        if(!k) return root;
        head->next=root;
        pre->next=nullptr;
        return rotateRight(head,--k);
    }
};
举报

相关推荐

0 条评论