/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
struct ListNode* rotateRight(struct ListNode* head, int k){ if (head == NULL) returnNULL; // Exception: empty list structListNode* preHead = head; structListNode* newHead = head; structListNode* newTail = head; structListNode* preTail = head; int ListSize = 1; // get the total size of the list as well as the previous tail of the list for (; preTail->next != NULL; preTail = preTail->next, ListSize++); k %= ListSize; if (k == 0) return head; // get the new tail of the new list // new head of the list is the successor of the new tail for (int i = 0; i < ListSize - k - 1; i++, newTail = newTail->next); newHead = newTail->next; newTail->next = NULL; // connect the previous tail to the previous head; preTail->next = preHead; return newHead; }