61. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

Example:

Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. 
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) 
            return head;
        ListNode dummy=new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;
        
        int i;
        for (i = 0; fast.next != null; i++)//让fast指向最后节点,i变成节点个数,此例子中i为5
            fast = fast.next; 
        
        for (int j = i - k % i; j > 0; j--)//j等于3,slow往前移动3次,移到3
            slow = slow.next;
        
        fast.next = dummy.next; //使得5指向1
        dummy.next = slow.next; //0指向4
        slow.next = null; //3指向null
        
        return dummy.next;        
    }
}
posted @ 2019-04-09 16:20  MarkLeeBYR  阅读(131)  评论(0)    收藏  举报