Monday, July 6, 2015

Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.
Have you met this question in a real interview? 
Yes

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
        int len = 0;
        ListNode run = head;
        if(head == null || head.next == null) return head;
        while(run != null){
            len++;
            run = run.next;
        }
       
        k = k % len;
        int m = len - k;
       
        ListNode nextHead = head;
        ListNode pre = null;
     
        while(m-- > 0){
            pre = nextHead;
            nextHead = nextHead.next;
        }
        pre.next = null;
        run = nextHead;
        while(run.next != null){
            run = run.next;
        }
       
        run.next = head;
        return nextHead;
       
    }
}

No comments:

Post a Comment