Created
February 16, 2013 12:29
-
-
Save pdu/4966711 to your computer and use it in GitHub Desktop.
Given a list, rotate the list to the right by k places, where k is non-negative. For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL. http://leetcode.com/onlinejudge#question_61
This file contains hidden or 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
| /** | |
| * Definition for singly-linked list. | |
| * struct ListNode { | |
| * int val; | |
| * ListNode *next; | |
| * ListNode(int x) : val(x), next(NULL) {} | |
| * }; | |
| */ | |
| class Solution { | |
| public: | |
| ListNode *rotateRight(ListNode *head, int k) { | |
| ListNode * tmp = head; | |
| ListNode * tail = head; | |
| int cnt = 0; | |
| while (tmp) { | |
| tail = tmp; | |
| tmp = tmp->next; | |
| cnt++; | |
| } | |
| if (cnt == 0) | |
| return NULL; | |
| k = k % cnt; | |
| if (k == 0) | |
| return head; | |
| else | |
| cnt = cnt - k; | |
| ListNode * ans = head; | |
| ListNode * prev = NULL; | |
| while (cnt--) { | |
| prev = ans; | |
| ans = ans->next; | |
| } | |
| if (prev) | |
| prev->next = NULL; | |
| if (tail) | |
| tail->next = head; | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment