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.


题解:首先注意一点是n可以比链表的length大。例如链表1->2,n=3,那么执行3次rotate的过程如下:

第一次:2->1;

第二次:1->2;

第三次:2->1;

那么我们是不是就要模拟了呢?答案是不用,只要用n = n%length就可以在一次遍历中完成转换。

还是快慢指针的思想,fast指针比slow指针快n+1步,当fast指针到达尾部时,slow指针的next元素就是新的链表头。还需要一个tail指针作为fast指针的前驱,并在最后利用tail指针把前半段链表链接起来。

代码如下:

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
private int getLength(ListNode head){
int answer = 0;
while(head != null){
answer++;
head = head.next;
} return answer;
} public ListNode rotateRight(ListNode head, int n) {
if(head == null || head.next == null)
return head; int length = getLength(head);
if(n == 0)
return head;
n = n % length; ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = head;
for(int i = 0;i < n;i++)
fast = fast.next; ListNode tail = fast;
while(fast != null){
slow = slow.next;
tail = fast;
fast = fast.next;
}
tail.next = dummy.next;
dummy = slow.next;
slow.next = null;
return dummy;
}
}

最新文章

  1. BZOJ2730: [HNOI2012]矿场搭建
  2. Sublime Text3 Package Control 在菜单栏中不显示
  3. HashMap、HashTable、LinkedHashMap和TreeMap用法和区别
  4. [luogu2982][USACO10FEB]慢下来Slowing down(树状数组+dfs序)
  5. web.config 加密/解密
  6. MySQL关闭过程详解和安全关闭MySQL的方法
  7. suse安装软件命令
  8. .Net Mvc4 Kendo Grid Demo
  9. Go - concurrency
  10. kickstart自动化安装--tftp+nfs+dhcp
  11. java基础:内存分配(上)
  12. mysql数据库的三范式的设计与理解
  13. MVPHelper更新日志 --- 新增常规分包模式
  14. Beta(5/7)
  15. formValidator 插件 使用总结
  16. Flex(ActionScript)与JavaScript交互的两种方式示例
  17. Linux下常用系统分析工具总结(转)
  18. 13. pt-ioprofile
  19. Node+Express+MongoDB + Socket.io搭建实时聊天应用实战教程(三)--前后端环境配置
  20. (原)关于获取ffmpeg解析rtsp流sdp中带有sps,pps的情况

热门文章

  1. 后期给项目加入Git版本控制
  2. html禁止图片拖拽移动在新窗口打开
  3. Swift_1_基本数据类型
  4. spring boot日志配置
  5. PHP性能:序——谈ab(Apache Bench)压力测试工具
  6. vue-router实现页面的整体跳转
  7. 批处理--执行sql(mysql数据库)
  8. 高仿微信app (含有发红包,聊天,消息等)用到 Rxjava+Retrofit+MVP+Glide技术
  9. hdu3579(线性同余方程组)
  10. 【BZOJ3168】[Heoi2013]钙铁锌硒维生素 高斯消元求矩阵的逆+匈牙利算法