LeetCode 61 rotating chain

Link: https: //leetcode-cn.com/problems/rotate-list

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

 

 

In fact this question is the rear to the front into the k nodes, but it is possible for the chain length is greater than the value k n, so to guarantee the modulo k must be less than n. Then requires two pointers point to the first node and the inverse of the penultimate nodes k + 1, and a method as before, first let down k steps forward pointer, let the first pointer and second pointer at the same time to go until the first a pointer to the penultimate node, when the second pointer points to the penultimate nodes k + 1.

Then start moving these k nodes, these k nodes to move as a whole, the first former head pointer to the first node, and then make the head node to the next node second pointer, and let the second pointer to air. The order must be right, otherwise it will error.

Although this question head node has changed, but does not delete files, so do not set up a virtual node.

c ++ code is as follows:

 1 class Solution {
 2 public:
 3     ListNode* rotateRight(ListNode* head, int k) {
 4         if(!head) return NULL;
 5         int n = 0;
 6         for(auto p = head; p; p = p->next){
 7             n++;
 8         }
 9         k %= n;
10         auto first = head, second = head;
11         while(k--){
12             first = first -> next;
13         }
14         while(first->next){
15             first = first->next;
16             second = second-> next;
17         }
18         first->next = head;
19         head = second->next;
20         second->next = NULL;
21         return head;
22     }
23 };

 

Guess you like

Origin www.cnblogs.com/hellosnow/p/11562298.html