[LeetCode] 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:
    ListNode *rotateRight(ListNode *head, int k) {
        if(head == nullptr || k <= 0)   return head;
        int len = listLength(head);
        k %= len;
        if(k == 0)  return head;
        ListNode *p = head, *new_head = head, *new_end = head;
        for(int i = 0; i < k; i++)
            p = p->next;
        while(p->next)
        {
            p = p->next;
            new_end = new_end->next;
        }
        new_head = new_end->next;
        new_end->next = nullptr;
        p->next = head;
        return new_head;
    }
    int listLength(ListNode *head)
    {
        int len = 0;
        while(head)
        {
            len++;
            head = head->next;
        }
        return len;
    }
};



你可能感兴趣的:([LeetCode] Rotate List)