LeetCode 61-- rotary list (the JAVA)

Given a list, the list of rotation, each node in the list is moved rightward  positions, wherein  is non-negative.

Example 1:

Input: 1-> 2-> 3-> 4- > 5-> NULL, k = 2 
Output: 4-> 5-> 1-> 2- > 3-> NULL 
explained: 
rotation to the right Step 1: 5- > 1-> 2-> 3-> 4- > NULL 
rotates clockwise 2 steps: 4-> 5-> 1-> 2- > 3-> NULL

Example 2:

Input: 0-> 1-> 2-> NULL , k = 4 
Output: 2->0->1->NULL
Explanation: 
rotation to the right Step 1: 2-> 0-> 1-> NULL 
rotates two steps to the right: 1-> 2-> 0- > NULL 
right rotation step 3:  0->1->2->NULL
rotating the right step 4: 2->0->1->NULL

Directly on the code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution 
{
    public ListNode rotateRight(ListNode head, int k) 
    {
        if(k==0)
            return head;
        if(head==null)
            return head;
        int length=1;
        ListNode cur=head;
        while(cur.next!=null) 
        { 
            CUR = cur.next; 
            length ++ ; 
        } 
        cur.next = head; // have already connected end to end chain on 
        int m = K%-length length; // this is the key to the algorithm, we should find where disconnect 
        for ( int I = 0; I <m; I ++ ) 
        { 
            CUR = cur.next; 
        } 
        ListNode newhead = cur.next; // get a new head node list 
        cur.next = null ; // off open-chain loop 
        return newhead; 
    } 
}

Algorithm idea: In fact, this can be interpreted as a mathematical problem, if k <chain length, in fact, can be understood as a front end to the list of k nodes entire move list, if k> length, mathematically study found that the actual It may be a k = k% length, the upper side to proceed. So complete understanding of the meaning of the title is very good solved.

 

Guess you like

Origin www.cnblogs.com/jiameng991010/p/11295498.html