Thursday, January 8, 2015

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.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        // k is counted from left to right (1-indexed).
        if (head==null || head.next==null)
            return head;

        int len = 1; // Length of list
        ListNode last = head;
        
        // After process, last points to the last node.
        while (last.next != null)
        {
            last = last.next;
            len++;
        }
        
        // In case k is larger than len
        int k = n % len;
        
        // If k point to the first node, the rotate list is itself.
        if (k == 0)
            return head;
            
        ListNode helper = new ListNode(0);
        helper.next = head;
        
        // pre node is the node before kth node.
        ListNode pre = head;
        
        for (int i = 0; i < len-k-1; i++)
            pre = pre.next;
            
        // Rotate
        last.next = helper.next;
        helper.next = pre.next;
        pre.next = null;
        
        return helper.next;
    }
}

No comments:

Post a Comment