[Leetcode 57] 61 Rotate List

Problem:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Analysis:

The first thought is to use the same strategy as in "Remove Kth Node in List" -- using two pointers, one is kth precedeeding the other. And once the former point to the null, the latter points to the place we need to set as new head. It seems this doesn't work in many cases.

Then the other solution is to first make the given list as a circle. And then go to the desired position to break the circle form a new list.

Code:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *rotateRight(ListNode *head, int k) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (head == NULL) return head;
15         
16         int cnt = 1;
17         ListNode *tmp = head;
18         while (tmp->next != NULL) {
19             tmp = tmp->next;
20             cnt++;
21         }
22         
23         tmp->next = head;
24         tmp = head;
25         int pos = cnt -  k % cnt;
26         while (--pos) {
27             tmp = tmp->next;
28         }
29         head = tmp->next;
30         tmp->next = NULL;
31         
32         return head;
33     }
34 };
View Code
原文地址:https://www.cnblogs.com/freeneng/p/3099812.html