leetcode题解-61. Rotate List
来源:互联网 发布:产品防伪码制作软件 编辑:程序博客网 时间:2024/06/01 21:45
题意:给出一个列表,往右旋转 k 个位置。
例子:给定链表 1->2->3->4->5->NULL 并且 k = 2,
返回链表 4->5->1->2->3->NULL.
分析:题目比较简单,分为三个部分来做。
1、计数,得到链表的长度。
2、找到新链表头部节点在旧链表中的前置节点,如上述例子中的节点3,同时节点3也是新链表的尾部。
3、进行对顺序变换的操作:
如果以fastNode指代节点5,slowNode指代节点3的话,该顺序变换的操作为:
fastNode.next = dummy.next;
dummy.next = slowNode.next;
slowNode.next = null;
值得注意的是,往右旋转k个位置,k有可能大于链表的长度,此时如果已经转了一遍的话,要再接着转,即在找slowNode时要进行k%len的操作。
那么代码就很容易写出来了:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null) return head; int len = 1; ListNode dummy = new ListNode(0); dummy.next = head; ListNode fastNode = head; while(fastNode.next != null){ fastNode = fastNode.next; len++; } ListNode slowNode = head; for(int i = 0; i < len - k % len - 1; i++){ slowNode = slowNode.next; } fastNode.next = dummy.next; dummy.next = slowNode.next; slowNode.next = null; return dummy.next; }}
阅读全文
0 0
- leetcode题解-61. Rotate List
- leetcode题解-61. Rotate List
- LeetCode题解:Rotate List
- LeetCode题解-61-Rotate List
- LeetCode 题解(37): Rotate List
- LeetCode题解——Rotate List
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- python 快速搭建http 文件共享服务器
- DxO PhotoLab(raw图片处理软件)官方正式版V1.1.0.2639下载 | DxO PhotoLab破解版
- redis集群
- 贪心poj2109
- angular自定义服务
- leetcode题解-61. Rotate List
- mysql数据库隔离性
- POJ2406 Power Strings 【KMP 或 后缀数组】
- 对现有FeatureClass添加字段的问题
- Unity3D中通过陀螺仪来控制摄像机的旋转
- [poj2318]:TOYS
- 编程新手教学龙书:最小化学习编程
- 2017最新最全的全国省市区行政单位五级四级三级地址数据库下载
- PID控制的MATLAB仿真(2)对PID控制的一些改进