61. Rotate List
Given the head of a linked list, rotate the list to the right by k places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { public: ListNode* rotateRight(ListNode* head, int k) { int size = head == nullptr ? 0 : 1; if(!size) return head; ListNode* current = head; while(current->next != nullptr) { current = current->next; size++; } current->next = head; k %= size; int move = size - k - 1; current = head; while(move--) { current = current->next; } head = current->next; current->next = nullptr;
return head; } };
|