leetcode第一刷_Rotate List
2014-05-12 12:51
232 查看
我提交了好多次,错误莫名其妙的,到后来才明白过来,原来我把题目给理解错了。
这个题的意思不是说让你把最后的那k个位置的元素移到前面来,这种问题的做法就是用两个指针,先让一个走,走到一定的长度之后两个一起走,很简单。它实际的意思是整个链表循环右移,假设一个链表长度是N,那么循环右移N次之后,链表又变回了原来的样子。k的取值范围只说了是非负的,也就是它可以是大于N的,因此实际的移位次数只是(k%N)而已。
代码就不多说了,很简单。
这个题的意思不是说让你把最后的那k个位置的元素移到前面来,这种问题的做法就是用两个指针,先让一个走,走到一定的长度之后两个一起走,很简单。它实际的意思是整个链表循环右移,假设一个链表长度是N,那么循环右移N次之后,链表又变回了原来的样子。k的取值范围只说了是非负的,也就是它可以是大于N的,因此实际的移位次数只是(k%N)而已。
代码就不多说了,很简单。
class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(!head||!head->next||k==0) return head; int i=0, len=0; ListNode *pre=head, *pNode = head, *newHead; while(pNode){ len++; pNode = pNode->next; } pNode = head; k %= len; if(k == 0) return head; while(i<k&&pNode){ pNode = pNode->next; i++; } while(pNode->next){ pre = pre->next; pNode = pNode->next; } newHead = pre->next; pre->next = NULL; pNode->next = head; return newHead; } };
相关文章推荐
- leetcode第一刷_Rotate List
- leetcode第一刷_Wildcard Matching
- Leetcode 第一题(Two Sum)
- 【leetcode每日一题】61.Rotate List
- leetcode_061 Rotate List
- 【Leetcode】61. Rotate List
- LeetCode第一题
- [LeetCode] Rotate List
- LeetCode 第一题剪彩自己的leetCode之路
- LeetCode第一题(c++)
- leetcode第一刷_Unique Binary Search Trees
- leetcode第一刷_Sort List
- leetcode第一刷_Longest Substring Without Repeating Characters
- leetcode第一刷_Sudoku Solver
- [leetcode刷题系列]Rotate List
- leetcode第一刷_Word Break II
- leetcode第一刷_Gas Station
- LeetCode_Rotate List
- leetcode第一刷_Unique Binary Search Trees II
- leetcode第一刷_Merge Sorted Array