Leetcode|快慢指针|61. 旋转链表

2022-01-10 15:10:03 浏览数 (1)

1 快慢指针

代码语言:javascript复制
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head || k == 0) return head;
        int size = 0;     
        auto node = head;
        // 记录链表长度为size
        while (node) {
            size  ;
            node = node->next;
        }
        // 快慢指针间隔的step
        int step = k % size;
        if (step == 0) return head;     // 边界判断
        auto slow = head, fast = head;  // 快慢指针
        for (int i = 0; i < step; i  )  // 快指针先走k步
            fast = fast->next;
        while (fast->next) {            // 快慢指针同时走到链尾
            slow = slow->next;
            fast = fast->next;
        }
        auto newhead = slow->next;      // 慢指针next对应nullptr,快指针next对应head
        slow->next = nullptr;
        fast->next = head;
        return newhead;
    }
};

0 人点赞