Rotate List
来源:互联网 发布:易语言用数据库做登录 编辑:程序博客网 时间:2024/05/19 14:51
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
.
一开始题目没看清 以为从前面开始进行逆转 其实是从后面开始计数 使用快慢指针 找到翻转点进行指针转换实现逆转 其中的注意点是这里的k是可以大于链表长度的 这个起初也没注意到 报错后才想到 所以第一步是计算链表长度len 然后针对 n%len进行翻转 代码如下:
public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head==null||head.next==null||n==0)return head;ListNode slow=head;ListNode fast=head;int count=0;while(fast!=null){ count++; fast=fast.next;}n=n%count;count=0;if(n==0) return head;fast=head;while(fast.next!=null){count++;if(count>n){fast=fast.next;slow=slow.next;}else{fast=fast.next;}}ListNode tmp=new ListNode(0);tmp.next=slow.next;fast.next=head;slow.next=null;return tmp.next; }}
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- cygwin *** 多个目标匹配。 停止
- log4j配置多个日志文件,输出特定的日志信息
- rtp协议分析
- C# ? and ??
- TCP三次握手、四次挥手
- Rotate List
- 拿来主义:与大家分享,关于wifi连接信息、管理、设置的CLASS
- 通过Sahara部署Hadoop集群
- C/C++中产生随机数(rand,srand用法)
- IrCut相关
- luncene 各种Query类详解实例
- JAVA连接Shake方法
- using关键字的几种用法
- 11.GridView、ListView等的OnItemClick事件无法触发的解决方案。