[leetcode] Rotate List
2013-01-28 03:26
274 查看
Given a list, rotate the list to the right by k places, where k is
non-negative.
For example:
Given
return
non-negative.
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function assert (k >= 0); if (head == NULL || k ==0) return head; ListNode *cur = head; int cnt = 0; while(cur!= NULL){ cur = cur->next; cnt++; } if (k >= cnt) k = k%cnt; cur = head; ListNode* previous = head; if (k == 0) return head; while(k>0){ cur = cur->next; k--; } while(cur->next){ previous = previous->next; cur = cur ->next; } ListNode* tempHead = previous->next; cur->next = head; previous->next = NULL; return tempHead; } };
相关文章推荐
- [LeetCode]Rotate List
- leetcode第一刷_Rotate List
- [Leetcode]Rotate List
- LeetCode: Rotate List
- LeetCode 61. Rotate List
- LeetCode 61. Rotate List
- LeetCode----- 61. Rotate List
- [LeetCode61]Rotate List
- Leetcode 061 Rotate List
- LeetCode | Rotate List
- Leetcode 61. Rotate List
- [LeetCode]Rotate List
- [Leetcode] Rotate List
- LeetCode-Rotate List
- [leetcode][list] Rotate List
- Rotate List--LeetCode
- [LeetCode] Rotate List
- Rotate List || LeetCode
- 【leetcode】Rotate List
- leetcode 61.Rotate List