Leetcode 61 -- 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.

Subscribe to see which companies asked this question.

 
Note: 注意K可能很大,可能会超时。
 
public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        
        ListNode before = head;
        ListNode after = head;
        
        // get length 
        int length = 0;
        while(after != null) {
            length++;
            after = after.next;
        }
    
        // get valid k less than length
        k = k % length;
        
        after = head;
        for(int i=0; i<k; i++) {
            after = after.next;
        }
        
        while (after.next != null) {
            before = before.next;
            after = after.next;
        }
        
        after.next = head;
        head = before.next;
        before.next = null;
        return head;
    }

 

posted on 2017-05-07 22:59  linxiong1991  阅读(111)  评论(0编辑  收藏  举报

导航