61. 旋转链表(Leetcode)

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 == NULL) return head;
        int sz = 0;
        ListNode* tail;
        for(auto a = head; a; a = a->next) {
            ++sz;
            tail = a;
        }
        k %= sz;
        tail->next = head;
        
        auto cur = head;
        for(int i = 0; i < sz - k - 1; ++i) cur = cur->next;
        head = cur->next;
        cur->next = NULL;

        return head;
    }

};
posted @ 2025-03-08 15:05  awei040519  阅读(8)  评论(0)    收藏  举报