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.
public ListNode rotateRight(ListNode head, int k) {
ListNode dummyHead = new ListNode(Integer.MIN_VALUE);
dummyHead.next = head;
ListNode node=head;
ListNode postnode=head;
if(head==null)
return null;
int count=1;
while(postnode.next!=null){
postnode=postnode.next;
count++;
}
//k值太大
k=k%count;
postnode=head;
for(int i=0;i
postnode=postnode.next;
}
while(postnode.next!=null){
postnode=postnode.next;
node=node.next;
}
//k值为0
if(node.next!=null){
dummyHead.next=node.next;
postnode.next=head;
}
else
dummyHead.next=head;
node.next=null;
return dummyHead.next;
}
阅读(345) | 评论(0) | 转发(0) |