61. 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.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getLen(ListNode* head)
    {
        int len = 0;
        while(head)
        {
            len++;
            head = head->next;
        }
        return len;
    }
  
    ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL) return NULL;
        ListNode* fast = head;
        int i;
        int len = getLen(head);
        k = k % len;
        if(k==0) return head;
        int n = len - k;
        for(i=1; i<n; i++)
        {
            fast = fast->next;
        }
       ListNode *head2 = fast->next;
       fast->next = NULL;
         ListNode* slow = head2;
       for(int j = 1; j <k; j++)
       {
           slow = slow->next;
       }
       slow->next = head;
       return head2;
       
    }
};


你可能感兴趣的:(61. Rotate List)