Skip to content

Instantly share code, notes, and snippets.

@barrysteyn
Created June 25, 2013 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barrysteyn/5861559 to your computer and use it in GitHub Desktop.
Save barrysteyn/5861559 to your computer and use it in GitHub Desktop.
Rotate List, from LeetCode
/**
* In an interview, the following questions should be asked:
* (1) What happens if k is longer than the list size
* (2) Edge cases (if head is NULL and k may be zero)
*
* Analysis: (where n is the number of nodes in the list)
* Time: O(n)
* Space: O(1)
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
ListNode *tail=head,
*kBehindTail=head;
if (!k || !head) return head;
for (int i=0; i < k; i++) {
tail=tail->next;
if (!tail) tail = head; //K longet than list size, so restart it again
}
while (tail->next) {
tail=tail->next;
kBehindTail=kBehindTail->next;
}
tail->next = head;
head = kBehindTail->next;
kBehindTail->next = NULL;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment