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.

思路:从length-k(k%length)处切段,把前半段接到后半段。1.扫一遍,扫到末尾的时候把末尾与头连上。2.扫到length-k(k%length)处,也就是3,3.next变成head,3.next变成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||k==0)
    {
        return head;
    }
    ListNode node=head;
    int size=1;
    while(node.next!=null)
    {
        node=node.next;
        size++;
    }
    node.next=head;
    k%=size;
    for(int i=0;i<size-k;i++)
    {
        node=node.next;
    }
    head=node.next;
    node.next=null;
    return head;
}
}

 

posted on 2016-10-09 03:02  Machelsky  阅读(129)  评论(0)    收藏  举报