欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 61. 旋转链表

程序员文章站 2022-05-20 19:10:03
...

旋转链表

/**
 * 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) return nullptr;
        int len = 0;
        ListNode *cur = head, *tail = cur;
        while(cur != nullptr){
            if(cur->next == nullptr) tail = cur;
            cur = cur->next;
            len++;
        }
        k = k%len;
        if(!k) return head;
        cur = head;
        ListNode* pre = nullptr;
        for(int i=0;i<len-k;i++){
            pre = cur;
            cur = cur->next;
        }
        pre->next = nullptr;
        tail->next = head;
        return cur;
    }
};
相关标签: LeetCode # LC链表