leetcode-61. 旋转链表
作者:互联网
leetcode-61. 旋转链表
题目:
代码:
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode():val(0),next(nullptr){}
ListNode(int x):val(x),next(nullptr){}
ListNode(int x,ListNode *next):val(x),next(next){}
};
ListNode* rotateRight(ListNode* head, int k) {
ListNode *rot=head;
int count=0;
while(rot){
count++;
rot=rot->next;
}
if(k==0 || count==0 ||count==1){
return head;
}
k=k%count;
if(k==0){
return head;
}
ListNode *p;
rot=head;
for(int i=1;i<count-k;i++){
rot=rot->next;
}
p=rot->next;
rot->next=nullptr;
ListNode *q=p;
for(int i=1;i<k;i++){
q=q->next;
}
q->next=head;
return p;
}
int main(){
ListNode* head;
int k;
ListNode* res;
res=rotateRight(head,k);
return 0;
}
标签:count,head,ListNode,int,next,链表,61,rot,leetcode 来源: https://blog.csdn.net/qq_42250642/article/details/120778540