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.

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
     public ListNode rotateRight(ListNode head, int k) {
    if (head == null) {
            return null;
        }

        if (head.next == null) {
            return head;
        }

        if (k <= 0) return head;

        int length = 0;
        ListNode runner = head;
        while (runner != null) {
            length += 1;
            runner = runner.next;
        }

        k = k % length;
        if (k == 0) {
            return head;
        }

        runner = head;
        int step = length - k - 1;

        for (int i = 1; i <= step; i++) {
            runner = runner.next;
        }

        ListNode newEnd = runner;
        ListNode newStart = runner.next;

        newEnd.next = null;

        runner = newStart;
        while (runner.next != null) {
            runner = runner.next;
        }

        runner.next = head;
        return newStart;
    }
}

results matching ""

    No results matching ""