Topic Link: Rotate List
Given a list, rotate the list to the right by K-places, where K is non-negative.
For example:
The requirement of this problem is to rotate the linked table K step to the right.
In fact, the list behind the L-k node to the front, you can use a fast and slow pointer processing. However, when K is greater than the list length L, problems can arise. A little bit of processing is needed when the fast pointer F points to the last node, and the next time it points to the head node, the problem is solved. This time complexity is O (k), so when K is very large, it will be tle.
when K is greater than L, the K-to-l mode can be processed. Therefore, the link table length is calculated first, and P points to the last node of the linked list. Next, K to the L modulus, and then the Q from the head node to move backward l-k step, so Q points to the position to be rotated. Finally, the node behind the Q is placed in front.
Assuming k=2, the list is followed by the following: NULL, 4, 3, 2, 0, 1 The collar p points to the last node of the list, Q points to the position to be rotated, i.e., 0, 1, 2, 3, 4, and so on. | | Q p Next put the node behind Q in front: 2, 1, 5, 4, 0, H | | P Q
When processing, the same first to the list header, easy to handle, similar to the Remove Nth Node from the End of the List, Swap Nodes in Pairs, Reverse Nodes in K-group, also first on the list header processing.
Time complexity: O (L) (L is the length of the list)
Space complexity: O (1)
1 class Solution2 {3 Public:4 ListNode *Rotateright(ListNode *Head, int k)5 {6 if(Head == NULL)7 return NULL;8 9 //Chain list plus head for easy handlingTen ListNode *h = New ListNode(0), *P, *Q; One h - Next = Head; A - int L = 0; - //P points to the last node the for(P = h; P - Next != NULL; ++ L, P = P - Next); - //Q point to the position to be rotated, that is, the last node after rotation - for(Q = h, k = L - k % L; k > 0; -- k, Q = Q - Next); - + //Put the second half of the list on the front - P - Next = h - Next; + h -Next = Q - Next; A Q - Next = NULL; at - return h - Next; - } - };
Reprint please indicate source: Leetcode---61. Rotate List
Leetcode---61. Rotate List