方法1
执行用时:8ms
语言:cpp
思路:求出链表长度,对旋转次数取模,逐位旋转
代码:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *p1 = head;
if(p1==NULL) return head;
ListNode *p2 = p1->next;
if(p2==NULL) return head;
int len = 0;
while(p1){
len++;
p1 = p1->next;
}
k %= len;
for(int i = 0;i < k;i++){
p1 = head;
p2 = p1->next;
while(p2->next){
p1 = p2;
p2 = p2 -> next;
}
p2->next = head;
head = p2;
p1->next = NULL;
}
return head;
}
};
方法2:
执行用时:8ms
语言:cpp
思路:求出链表长度,对旋转次数取模,选择一个区间旋转,较第一种方法更快,只需一趟遍历
代码:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *p1 = head;
if(p1==NULL) return head;
ListNode *p2 = p1->next;
if(p2==NULL) return head;
int len = 0;
while(p1){
len++;
p1 = p1->next;
}
k %= len;
p1 = p2 = head;
for(int i = 0;i < k;i++){
p2 = p2 -> next;
}
while(p2->next){
p2 = p2->next;
p1 = p1->next;
}
p2->next = head;
head = p1->next;
p1->next = NULL;
return head;
}
};