Created
July 10, 2014 07:52
-
-
Save walkingtospace/99aaf9abbe6021fbb811 to your computer and use it in GitHub Desktop.
rotate-list
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
https://oj.leetcode.com/problems/rotate-list/ | |
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
/* | |
k=2 | |
1->2->3->4->5 | |
. . | |
1->2->3->4->5 | |
. . | |
4->5->1->2->3 | |
k=4; | |
1->2->3->4->5 | |
. . | |
2->3->4->5->1 | |
k=5; | |
1->2->3->4->5 | |
.. | |
//if first==second then return head | |
k=7(same as k=2); | |
1->2->3->4->5 | |
. . | |
4->5->1->2>3 | |
test cases | |
{}, 0 | |
{1}, 1 | |
{1,2}, 1 | |
{1,2}, 2 | |
{1,2}, 3 | |
*/ | |
class Solution { | |
public: | |
ListNode *rotateRight(ListNode *head, int k) { | |
if(k <=0 || head == NULL) return head; | |
ListNode* first = head; | |
ListNode* second = head; | |
//shift k nodes | |
for(int i=0; i<k ; i++) { | |
second = second->next; | |
if(second == NULL) { | |
k -= i; | |
i = 0; | |
second = head; | |
} | |
} | |
if(head == second) return head; | |
while(second->next) { | |
first = first->next; | |
second = second->next; | |
} | |
second->next = head; | |
head = first->next; | |
first->next = NULL; | |
return head; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment