Created
June 25, 2013 19:27
-
-
Save barrysteyn/5861559 to your computer and use it in GitHub Desktop.
Rotate List, from LeetCode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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