【leetcode刷题笔记】Rotate List
2024-08-29 01:52:13
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;
}
}
最新文章
- BZOJ2730: [HNOI2012]矿场搭建
- Sublime Text3 Package Control 在菜单栏中不显示
- HashMap、HashTable、LinkedHashMap和TreeMap用法和区别
- [luogu2982][USACO10FEB]慢下来Slowing down(树状数组+dfs序)
- web.config 加密/解密
- MySQL关闭过程详解和安全关闭MySQL的方法
- suse安装软件命令
- .Net Mvc4 Kendo Grid Demo
- Go - concurrency
- kickstart自动化安装--tftp+nfs+dhcp
- java基础:内存分配(上)
- mysql数据库的三范式的设计与理解
- MVPHelper更新日志 --- 新增常规分包模式
- Beta(5/7)
- formValidator 插件 使用总结
- Flex(ActionScript)与JavaScript交互的两种方式示例
- Linux下常用系统分析工具总结(转)
- 13. pt-ioprofile
- Node+Express+MongoDB + Socket.io搭建实时聊天应用实战教程(三)--前后端环境配置
- (原)关于获取ffmpeg解析rtsp流sdp中带有sps,pps的情况
热门文章
- 后期给项目加入Git版本控制
- html禁止图片拖拽移动在新窗口打开
- Swift_1_基本数据类型
- spring boot日志配置
- PHP性能:序——谈ab(Apache Bench)压力测试工具
- vue-router实现页面的整体跳转
- 批处理--执行sql(mysql数据库)
- 高仿微信app (含有发红包,聊天,消息等)用到 Rxjava+Retrofit+MVP+Glide技术
- hdu3579(线性同余方程组)
- 【BZOJ3168】[Heoi2013]钙铁锌硒维生素 高斯消元求矩阵的逆+匈牙利算法