Rotate List
来源:互联网 发布:中国税务网络大学手机 编辑:程序博客网 时间:2024/05/24 06:53
问题描述
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.
思考:用两个指针A,B,A先走k步,然后A、B同时
想法
- 1、A先走k步,然后A、B同时,直到A到表尾
- 2、head指向B的next;
- 3、将A的next指向表头,B的next置为null;
代码
public class Solution { public ListNode rotateRight(ListNode head, int k) { ListNode first = head; ListNode second = head; if(head == null || head.next == null) return head; int sum = 0; while(k > 0){ first = first.next; sum++; k--; if(first == null){ first = head; k = k % sum; } } while(first.next != null){ first = first.next; second = second.next; if(second == null) second = head; } first.next = head; head = second.next; second.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
- Silverlight学习笔记十八最简单的添加双击事件的实现方法
- 总结 & 思考 & 平常心
- 山寨QQ新得
- C#操作word定位光标
- jsp 返回并刷新上一页
- Rotate List
- 线程特定数据 Thread Specified Data
- Mysql中的注释
- 立场声明--“没有丑女人只有懒女人;没有牛X的人,勤奋的你会比他更牛X”
- 【微积分】CodeForces 185B Mushroom Scientists
- 使用corosync+pacemaker构建高可用集群(转)
- intent传递对象——序列化
- Loading Large Bitmaps Efficiently
- 点滴积累