lintcode-medium-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 and k = 2, return 4->5->1->2->3.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        if(head == null || head.next == null)
            return head;
        
        int len = 0;
        
        ListNode p = head;
        while(p != null){
            p = p.next;
            len++;
        }
        
        k %= len;
        
        if(k == 0)
            return head;
        
        p = head;
        for(int i = 1; i < len - k; i++)
            p = p.next;
        
        ListNode head2 = p.next;
        p.next = null;
        p = head2;
        
        while(p != null && p.next != null)
            p = p.next;
        
        p.next = head;
        
        return head2;
    }
}

 

posted @ 2016-04-05 12:24  哥布林工程师  阅读(103)  评论(0编辑  收藏  举报