Rotate List
来源:互联网 发布:万达电商 数据百家号 编辑:程序博客网 时间:2024/06/06 08:36
Rotate List
思路:设置两个指针p,q,相差n步,然后p,q同时前进,当q到最后一个节点时,p所指向的节点是倒数第n个节点的前一个节点。
例如1,2,3,4,n=3,p,q相差3步,当q指向4时,p指向1,1是2的前一个节点,2正是倒数第3个节点。
当n=4时,倒数第4个节点正是头结点,实际上无需旋转链表,直接返回就好。
找到节点p后,q此时是最后一个节点,再做一些操作即可。
特别注意:
传入的参数n可以很大,比链表的长度还要大,实际上,只需要向右循环移动len%n步就可以了,所以一开始要遍历一遍list,得到它的的长度。
public ListNode rotateRight(ListNode head, int n) { if(head==null || head.next==null){ return head; } ListNode pos=head,p=head,q=head; int len=0; while(pos!=null){ len++; pos=pos.next; } int i=0; n=n%len; while(i<n){ if(q.next==null){ return head; } q=q.next; i++; } while(q.next!=null){ p=p.next; q=q.next; } q.next=head; head=p.next; p.next=null; return head; }
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
- sed命令详解
- 一步一步学习openfire+spark(2)——介绍几个概念
- Oracle 11gR2 使用 RMAN duplicate from active database 复制数据库
- C++ STL 中 map 容器的说明和使用技巧 .
- 误: Automation 服务器不能创建对象 解决方案
- Rotate List
- mysql慢查询
- 用户界面设计
- C++实现String类
- CAShapeLayer和CAGradientLayer使用
- 『黑马程序员』第十三话<银行业务调度系统>
- 在终端中配置环境变量
- uva 138 Street Numbers
- 杭电 1013