LeetCode: Rotate List

Problem:

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:
    ListNode *rotateRight(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL) return NULL;
        ListNode* node = head;
        int count = 1;
        while (node->next != NULL)
        {
            node = node->next;
            ++count;
        }
        
        node->next = head;
        k = k % count;
        int step = count - k - 1;
        node = head;
        while (step > 0)
        {
            --step;
            node = node->next;
        }
        
        head = node->next;
        node->next = NULL;
        return head;
    }
};


你可能感兴趣的:(function,list,struct,null)