码迷,mamicode.com
首页 > 其他好文 > 详细

61. Rotate List

时间:2019-04-09 16:32:40      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:class   head   tno   nbsp   lis   ast   example   bsp   slow   

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;        
    }
}

61. Rotate List

标签:class   head   tno   nbsp   lis   ast   example   bsp   slow   

原文地址:https://www.cnblogs.com/MarkLeeBYR/p/10677711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!