61. Rotating list

Time:2020-3-21

Given a list, rotate the list, and move each node of the list to the right by K positions, where k is a non negative number.

Example 1:

Input: 1 – > 2 – > 3 – > 4 – > 5 – > null, k = 2
Output: 4 – > 5 – > 1 – > 2 – > 3 – > null
Interpretation:
Rotate 1 step to the right: 5 – > 1 – > 2 – > 3 – > 4 – > null
Rotate 2 steps to the right: 4 – > 5 – > 1 – > 2 – > 3 – > null
Example 2:

Input: 0 – > 1 – > 2 – > null, k = 4
Output: 2 – > 0 – > 1 – > null
Interpretation:
Rotate 1 step to the right: 2 – > 0 – > 1 – > null
Rotate 2 steps to the right: 1 – > 2 – > 0 – > null
Rotate 3 steps to the right: 0 – > 1 – > 2 – > null
Rotate 4 steps to the right: 2 – > 0 – > 1 – > null

One of the more troublesome points of the list is that it can only walk in one direction. My idea is to first determine the length of the list and the points to move.

public ListNode rotateRight(ListNode head, int k) {
    if(head==null) return head;
    ListNode cur=head; 
    int len=0;
    while(cur!=null){
        cur=cur.next;
        len++;
    }
    k=k%len;
    cur=head;
    for(int i=0;i<len-k-1;i++) cur=cur.next;
    ListNode newHead=cur.next;
    if(newHead==null) return head;
    cur.next=null;
    cur=newHead;
    while(cur.next!=null) cur=cur.next;
    cur.next=head;
    return newHead;
}

The answer is more ingenious. First, close him into a ring, and then make sure the position is broken.

public ListNode rotateRight(ListNode head, int k) {
    if(head==null) return head;
    int len=1;
    ListNode cur=head;
    while(cur.next!=null){
        cur=cur.next;
        len++;
    }
    cur.next=head;
    ListNode newTail=head;
    for(int i=0;i<len-k%len-1;i++) newTail=newTail.next;
    ListNode newHead=newTail.next;
    newTail.next=null;
    return newHead;
}