Saturday, November 14, 2015

[leetcode] Rotate List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * 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 || head.next == null) return head;
        int length = 0;
        ListNode current = head;
        ListNode previous = null;
        while (current != null){
            length++;
            previous = current;
            current = current.next;
        }
        k = k % length;
        if (k == 0) return head;
        ListNode fast = head;
        for (int i = 0; i < k; i++){
            fast = fast.next;
        }
        ListNode newEnd = null;
        ListNode newStart = head;
        while (fast != null){
            newEnd = newStart;
            newStart = newStart.next;
            fast = fast.next;
        }
        previous.next = head;
        newEnd.next = null;
        return newStart;
    }
}

No comments:

Post a Comment