您的位置:首页 > 其它

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
1->2->3->4->5->NULL
and 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: