One. Problem Description
Given a list, the list of rotation, each of the node list to the right by k positions, wherein k is non-negative.
Example 1:
Input: 1-> 2-> 3-> 4-> 5-> NULL, k = 2
Output: 4-> 5-> 1-> 2-> 3-> NULL
Explanation:
Rotate Right Step 1: 5-> 1-> 2-> 3-> 4-> NULL
Rotate right Step 2: 4-> 5-> 1-> 2-> 3-> NULL
Example 2:
Input: 0-> 1-> 2-> NULL, k = 4
Output: 2-> 0-> 1-> NULL
Explanation:
Rotate Right Step 1: 2-> 0-> 1-> NULL
Rotate right Step 2: 1-> 2-> 0-> NULL
Rotate Right Step 3: 0-> 1-> 2-> NULL
Rotate Right Step 4: 2-> 0-> 1-> NULL
two. Problem-solving ideas
Step one: the last cycle to find a single linked list, it points to the next node of the first node, this time forming a circular list.
Step two: the length of the length to obtain the list, then we can know that the mobile is actually the k-1 cycle to find the beginning of the chain length-k rearwardly from the first node a knot length =% nodes get right.
Step three: Disconnect the node formed null, this time into a circular list and single linked list, and the next node is the head node.
three. Results of the
When execution: 1 ms, beat the 99.90% of all users in Java submission.
Memory consumption: 35.8 MB, defeated 82.91% of all users in Java submission.
four. Java code
class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null||k==0) { return head; } ListNode first=head; ListNode second=head; while(true) { if(second.next==null) { break; } second=second.next; } int length=0; ListNode m=head; while(m!=null) { length++; m=m.next; } second.next=first; length=length-k%length; for(int i=1;i<length;i++) { first=first.next; } second=first; first=first.next; second.next=null; return first; } }