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.

Solution:

将链表头尾相接组成一个环,然后走(size - k%size)步,后面的节点断开,就是位移后的列表。

public ListNode rotateRight(ListNode head, int k) {
    if(head == null || k == 0) return head;
    int size = 1;
    ListNode node = head;
    while(node.next != null) {
        node = node.next;
        size++;
    }
    node.next = head;
    int n = size - k%size;
    for(int i=0; i<n; i++) {
        node = node.next;
    }
    ListNode h = node.next;
    node.next = null;
    return h;
}

 

你可能感兴趣的:(LeetCode 61 - Rotate List)