首页 > 代码库 > Rotate List

Rotate List

思路:先对List进行一次遍历,得到长度,第二次遍历时从(length-k%length)处切开即可,这里需要注意第一次遍历结束后指针停留在最后一个元素处,第二次遍历时这个指针便相当于头指针,方便~

/**
 * 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 == nullptr)
            return nullptr;
            
        ListNode *cur = head;
        int length = 1;
        while(cur->next != nullptr)
        {
            cur = cur->next;
            ++length;
        }
        cur->next = head;
        
        int count = length - k%length;
        while(count>0)
        {
            cur = cur->next;
            --count;
        }
        head = cur->next;
        cur->next = nullptr;
        return head;
    }
};

 

Rotate List