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.

Solution:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head==null||head.next==null || n==0) return head;
ListNode fakeHead = new ListNode(0);
fakeHead.next=head;
int length=0;
ListNode start=fakeHead, end=fakeHead;
for(int i=0; i<n; i++){
if(end.next==null) break;
end=end.next;
length++;
}
if(end.next==null){
//when n>=length
//int startPos = (length-n)%length+length; //Or:
int startPos=n%length;
if(startPos==0) return fakeHead.next;
startPos=length-startPos; for(int i=0; i<startPos; i++){
start=start.next;
}
}
else{
while(end.next!=null){
start=start.next;
end=end.next;
}
}
//reorder list
end.next=fakeHead.next;
fakeHead.next=start.next;
start.next=null;
return fakeHead.next; }
}

Note:假设end后移n次后end.next还不是null,说明list的长度>n。则将start和end总体后移。

否则,说明list的长度<=n,这时候须要找到rotate的实际次数。对于一个长为length的list,若rotate的次数为length,则结果为原list。所以rotate的实际次数是n%length,若结果为0,则直接返回原list;否则,须要找到对应的start点,即改动list的起始点。

注意代码中

 int startPos = (length-n)%length+length;      

事实上和

int startPos=n%length;
startPos=length-startPos;

一个效果(startPos不为0时)。可是后者比較好理解。

另外一个负数对一个正数取模,计算例如以下:

result=m%n, where m<=0, n>0

Assume m=xn+result, where x<=0, result<0 and -result<n.

比方(-5)%3。 -5=3*(-1)+(-2)。所以(-5)%3=-2。

最新文章

  1. 【用xocde5打包 在IOS7以下也能显示无默认gloss 效果 图解】
  2. Android项目部署时,发生AndroidRuntime:android.view.InflateException: Binary XML file line #168: Error inflating class错误
  3. css3的基本样式
  4. input 边框颜色
  5. 只会CSS还不够,LESS、SASS、BootStrap、Foundation一网打尽!
  6. Scala 深入浅出实战经典 第53讲:Scala中结构类型实战详解
  7. c++ 职责链模式(Chain of Responsibility)
  8. 字母排列_next_permutation_字典序函数_待解决
  9. thinkphp 一个页面使用2次分页的方法
  10. python操作mongodb之六自定义类型存储
  11. 解决oracle11g安装导致数据库无法自动搜集统计信息-转
  12. angularjs $state.go 传参
  13. android 实现模拟按键
  14. MySql中启用InnoDB数据引擎的方法
  15. FragmentTransaction.addToBackStack无效的问题
  16. openresty nginx 安装过程记录
  17. python --- hashlib模块使用详解
  18. 痞子衡嵌入式:恩智浦MCU安全加密启动一站式工具NXP-MCUBootUtility用户指南
  19. jquery cookie问题
  20. 有状态(Stateful)与无状态(Stateless)

热门文章

  1. What the difference between rebuild index and re-organize index?
  2. 两个div在同一行,两个div不换行
  3. MD5加密,解密
  4. uva 1557 - Calendar Game(博弈)
  5. firefox os 2.1版本号UI接口方面有了质的飞跃
  6. ArcGIS SDE 10.1 for Postgresql 服务连接配置
  7. 部署Win Server 2012十项注意
  8. 【设计模式】Template Method模式
  9. Android MVC MVP
  10. OpenCV面、人眼检测