LeetCode - M- Rotate List

題意

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

解法

注意點:對於超出鏈表長度的k,取餘數

實現

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == NULL || k <= 0) return head;
        int idx = 1;
        ListNode* fast = head;
        //get length
        while(fast->next != NULL){
            ++idx;
            fast = fast->next;
        }
        k = k % idx;
        if(k == 0) return head;
        fast = head;
        ListNode* slow = head;
        ListNode* pre = NULL;
        idx = 1;
        while(idx < k && fast->next != NULL){
            ++idx;
            fast = fast->next;
        }
        while(fast->next != NULL){
            fast = fast->next;
            pre = slow;
            slow = slow->next;
        }
        pre->next = NULL;
        fast->next = head;
        head = slow;
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章