170.Rotate List
1.Description(Medium)
Given a list, rotate the list to the right byk
places, where_k_is non-negative.
Example
Given1->2->3->4->5
and k =2
, return4->5->1->2->3
.
2.Code
从head开始跑,知道最后一个节点,这是可以得到链表的长度len,将尾指针指向头指针,形成circle.
这时再向前跑len-k%len,从这里断开即可。注意这里,因为K可能很大,比len还大很多,所以不能len-k,而是len-k%len
另一个要注意的是算len,是current.next!=null,否则会nullpointerexception.len也是从1开始。
public ListNode rotateRight(ListNode head, int k) {
if(head==null){
return head;
}
ListNode current=head;
int len=1;
while(current.next!=null){
len++;
current=current.next;
}
current.next=head;
ListNode temp=current;
for(int i=0;i<len-k%len;i++){
temp=temp.next;
}
ListNode newhead=temp.next;
temp.next=null;
return newhead;
}
Last updated
Was this helpful?