LeetCode 61. Rotate List
2016-04-12 23:21
281 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
Need to pay attention to the K value. k = k % length
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
Need to pay attention to the K value. k = k % length
ListNode* rotateRight(ListNode* head, int k) { if(!head || !head->next) return head; ListNode* tmp = head; int length = 0; while(tmp) { length++; tmp = tmp->next; } k = k % length; // k might be larger than the length of the linked list. if(k == 0) return head; // remember to check k value ListNode* fast = head; ListNode* slow = head; while(k > 0) { fast = fast->next; k = k - 1; } while(fast && fast->next) { slow = slow->next; fast = fast->next; } ListNode* newHead = slow->next; slow->next = NULL; fast->next = head; return newHead; }
相关文章推荐
- Matlab、C++混合编程调用OpenCV
- C++作业3
- 百度翻译
- 强连通从入门到精通
- MSP432--TimerA (主要说明如何实现可调PWM)
- Anliven - 解决问题的一些方法
- 用qemu模拟i386的linux内核,用于内核学习
- python安装第三方库
- 电子钱包的圈存——java card开发第四篇
- C++实验3—本月有几天?
- C++作业3
- PHP是如何执行代码解析过程的
- 程序员面试那些事儿
- 浅析ADO.NET五大对象
- iOS开发中对数组元素进行排序
- Spark RDD缓存代码分析
- SearchBar放至UINavigationBar
- Mac OS X 下查看和设置JAVA_HOME
- Cocos2d 控件:创建一个label
- Cocos2d 创建一个精灵