题目
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head==nullptr)
return nullptr;
auto ptr = head;
int length = 0;
while (ptr != nullptr)
{
ptr = ptr->next;
length++;
}
k=k%length;
if(k==0)
return head;
//54321 2
auto newHead = ReverseList(head, length);
if(k==length)
return newHead;
//45321 2
newHead = ReverseList(newHead, k);
//45123 2
int num = k;
auto nextHead = newHead;
while (num > 0)
{
nextHead = nextHead->next;
num--;
}
auto nextNewHead=ReverseList(nextHead, length - k);
auto connPtr = newHead;
while (k > 1)
{
connPtr = connPtr->next;
k--;
}
connPtr->next = nextNewHead;
return newHead;
}
/*
* head 开始结点
* num 翻转的个数
* return 反转后的头结点
*/
ListNode* ReverseList(ListNode*head, int num)
{
if (head == nullptr || num == 0)
return nullptr;
auto realTail = head;
ListNode* newHead = nullptr;
ListNode* temp = nullptr;
while (num>0)
{
temp = head->next;
head->next = newHead;
newHead = head;
head = temp;
num--;
}
realTail->next = temp;
return newHead;
}
};