Rotate List

Rotate List

问题:

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

思路:

  简单的数学推导问题

我的代码:

public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if(head == null || n <= 0) return head;
        int len = 0;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode tail = dummy;
        ListNode cur = head;
        while(cur != null)
        {
            cur = cur.next;
            tail = tail.next;
            len++;
        }
        int gap = len - n%len;
        ListNode last = dummy;
        for(int i = 0; i < gap; i++)
        {
            last = last.next;
        }
        tail.next = dummy.next;
        dummy.next = last.next;
        last.next = null;
        return dummy.next;        
    }
}
View Code

 

posted on 2015-03-13 16:32  zhouzhou0615  阅读(114)  评论(0编辑  收藏  举报

导航