leetcode第一刷_Rotate List
来源:互联网 发布:sql 清空数据库事务 编辑:程序博客网 时间:2024/05/21 11:18
我提交了好多次,错误莫名其妙的,到后来才明白过来,原来我把题目给理解错了。
这个题的意思不是说让你把最后的那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; }};
0 0
- leetcode第一刷_Rotate List
- leetcode第一刷_Rotate Image
- leetcode第一刷_Sort List
- leetcode第一刷_Partition List
- leetcode第一刷_Insertion Sort List
- leetcode第一刷_Linked List Cycle
- leetcode第一刷_Linked List Cycle II
- leetcode第一刷_Reverse Linked List II
- leetcode第一刷_Copy List with Random Pointer
- leetcode第一刷_ Flatten Binary Tree to Linked List
- leetcode第一刷_Convert Sorted List to Binary Search Tree
- leetcode第一刷_Remove Duplicates from Sorted List II
- leetcode 第一刷_Remove Nth Node From End of List
- leetcode第一刷_Candy
- leetcode第一刷_Triangle
- leetcode第一刷_Combinations
- leetcode第一刷_Anagrams
- leetcode第一刷_Permutations
- OFFER
- Codeforces 430B Balls Game
- Java Transaction API
- Linux作业(三)-shell统计某文章中出现频率最高的N个单词并排序输出出现次数
- Spring.x+Hibernate
- leetcode第一刷_Rotate List
- Java IO流学习总结
- UNCOMMENT THE
- 用户态和内核态的概念区别
- Web_JavaScript_客户端监测;
- java 之网格布局管理器;
- APK安装位置
- FileUpload
- 用UDP实现HTTP Streaming协议从指定的URL拉流