LeetCode question: rotating list

 
Original title:
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
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
explained:
rotation to the right Step 1: 2-> 0-> 1-> NULL
rotates clockwise 2 step: 1-> 2-> 0-> NULL
rotated clockwise step 3: 0-> 1-> 2-> NULL
rotation step 4 right: 2-> 0-> 1-> NULL
Solution: In fact, from the title contains the problem-solving ideas, "spin", is not necessary to have a ring to rotate. Ideas: first one-way linked list into circular linked list, and then the rotation, to find a new head node, then the head node is a next node point to null, so that, put the disconnected circular linked list, the new list obtained.
/ ** 
* rotary list
*
* @param head
* @param K
* @return
* /
public ListNode RotateRight (ListNode head, int K) {
IF (head == null) {
return null;
}
ListNode Current = head;
// chain length
int length =. 1;
the while (! current.next = null) {
Current = current.next;
length + =. 1;
}
// into the circular list
current.next = head;

// the new position of the head node
index = int (length - (K% length));

IF (index == 0) {
return head;
}
Current = head;
// find new head node
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
head = current.next;
//断开链表
current.next = null;

return head;
}

 

Guess you like

Origin www.cnblogs.com/aibaofeng/p/11098773.html