1. 程式人生 > 其它 >【力扣 091】61. 旋轉連結串列

【力扣 091】61. 旋轉連結串列

61. 旋轉連結串列

給你一個連結串列的頭節點 head ,旋轉連結串列,將連結串列每個節點向右移動 k 個位置。

示例 1:


輸入:head = [1,2,3,4,5], k = 2
輸出:[4,5,1,2,3]
示例 2:


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

提示:

連結串列中節點的數目在範圍 [0, 500] 內
-100 <= Node.val <= 100

來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/rotate-list
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

程式碼實現:

/**
 * 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 head;
        ListNode *p = head;
        int num = 0;
        while(p)
        {
            ++num;
            p = p->next;
        }
        if(k % num == 0) return head;
        k = k % num;

        ListNode *slow = head, *fast =head;
        while(k--)
            fast = fast->next;
        while(fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }
        p = slow->next;
        slow->next = nullptr;
        fast->next = head;
        return p;
    }
};