leetcode--Rotate List
2015-06-08 09:20
295 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null) return null;
int n = 0;
ListNode p = head;
ListNode tail = null;
while(p!=null){
if(p.next==null) tail=p;
p = p.next;
n++;
}
if(k!=0){
k = (k-1)%n+1;
k = n-k;//k为序号
}
if(k==0){
return head;
}
p = head;
while(k>1){
p = p.next;
k--;
}
if(p.next==null){
return head;
}
ListNode h = p.next;
tail.next = head;
p.next = null;
return h;
}
}
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL./**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null) return null;
int n = 0;
ListNode p = head;
ListNode tail = null;
while(p!=null){
if(p.next==null) tail=p;
p = p.next;
n++;
}
if(k!=0){
k = (k-1)%n+1;
k = n-k;//k为序号
}
if(k==0){
return head;
}
p = head;
while(k>1){
p = p.next;
k--;
}
if(p.next==null){
return head;
}
ListNode h = p.next;
tail.next = head;
p.next = null;
return h;
}
}
相关文章推荐
- jQuery checkbox“checked”返回 undefined
- libsqlite3.dylib与libsqlite3.0.dylib的区别
- Android批量图片加载经典系列——采用二级缓存、异步加载网络图片
- 给字符数组赋值的方法
- Linux内核Backlog笔记
- jQuery粘性跟随滚动条滚动的导航栏源代码下载
- 解读郭神LitePal源码-litepal.xml的解析
- OracleOraDb11g_home1TNSListener服务启动后自动停止
- myeclipse如何切换用户
- 出色的 JavaScript API 设计秘诀
- ASP.NET中Global.asax 文件是什么?
- jQuery背景跟随鼠标移动的网页导航
- JAVA 变量
- uva1484
- 利用底层键盘钩子屏蔽任意按键
- Math.round(11.5)等于多少?Math.round(-11.5)等于多少?
- python 使用scapy进行ARP扫描
- C++9.3.8 赋值与swap
- android之layout布局和ListView中的一些属性介绍
- jQuery ui背景色动态渐变导航菜单