LeetCode - Rotate List
2015-12-27 17:26
363 查看
题目:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
思路:
此题和Remove Nth Node from End of List类似,但首先得统计总的个数
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
思路:
此题和Remove Nth Node from End of List类似,但首先得统计总的个数
package list; public class RotateList { public ListNode rotateRight(ListNode head, int k) { if (k == 0 || head == null) return head; ListNode x = head; int count = 0; while (x != null) { ++count; x = x.next; } int n = k; if (k >= count) { if (k % count == 0) return head; else n = k % count; } ListNode p = head; ListNode q = head; while (p != null && n > 0) { p = p.next; --n; } while (p.next != null && q.next != null) { p = p.next; q = q.next; } ListNode newhead = q.next; p.next = head; q.next = null; return newhead; } public static void main(String[] args) { // TODO Auto-generated method stub RotateList r = new RotateList(); ListNode a1 = new ListNode(1); ListNode a2 = new ListNode(2); ListNode a3 = new ListNode(3); ListNode a4 = new ListNode(4); ListNode a5 = new ListNode(5); a1.next = a2; a2.next = a3; a3.next = a4; a4.next = a5; a5.next = null; ListNode head = r.rotateRight(a1, 2); while (head != null) { System.out.println(head.val); head = head.next; } } }
相关文章推荐
- 关于web性能的思考与分享[10]-fis3构建工具-语法教程(2)之定位资源
- Java基础之switch语句
- 23种设计模式(15)_行为型_迭代器模式(Iterator Pattern)
- 34.UIImage — 把多张图片合成一张图
- 世界是数字的4
- IOS 基础动画Core Animation
- 从 最大似然到EM详解
- 网络传输层TCP协议InputStream read方法是否返回-1
- 关于宽度高度-css 傻傻分不清楚
- ios uicollectionview
- Kindeditor的使用
- office2007安装找不到Office.zh-cn/OfficeLR.cab问题
- linux 字符界面浏览器 w3m(转)
- ios - objectC 的isa 详解
- jQuery $.each用法
- 芒果iOS开发之 CONFLICT (content): AutoMatic merge failed;fix conflicts and then commit the result.
- Js-Html 前端系列--checkbox
- 单例模式
- 问题分析-无界线程池误用导致OOM:java.lang.OutOfMemoryError:unable to create new native thread
- CDN模式介绍