Rotate 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->NULL and k = 2,
return 4->5->1->2->3->NULL.

这个题本身没难度,就是有一点,要注意这里要k可以大于n,这个时候取余就行了。

public ListNode rotateRight(ListNode head, int k) {
    int n=1;
    if(head==null||head.next==null)
        return head;
    ListNode pre=head,cur=head.next;
    while(cur!=null){
        cur=cur.next;
        pre=pre.next;
        n++;
    }
    k=k%n;
    cur=head;
    while(n-k>0){
        pre.next=cur;
        cur=cur.next;
        n--;
        pre=pre.next;
    }
    pre.next=null;
    return cur;
}

你可能感兴趣的:(java,LeetCode,链表)