题目:

个人解答:
递归方法解答。注意测试用例中有k值超过链表数量,此时应当取k%链表数量来减少循环。
/*** Definition for singly-linked list.* 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) {}* };*/class Solution {public:ListNode* rotateRight(ListNode* head, int k) {if(!head||!head->next||k==0)return head;ListNode* dummy = new ListNode(0,head);int count_total = 0;while(head){head=head->next;count_total++;}head = dummy->next;k = k % count_total;if(k==0||k=count_total)return head;if(k==1){int value_n = head->val, value_nn = 0;int temp = 0;while(head->next->next){temp = value_n;value_n = head->next->val;value_nn = head->next->next->val;head->next->val = temp;head = head->next;}if(!dummy->next->next->next){dummy->next->val = head->next->val;dummy->next->next->val = value_n;}else{head->next->val = value_n;dummy->next->val = value_nn;}return dummy->next;}else{head = rotateRight(rotateRight(head,k-1),1);}return head;}};
官方解答:
思路:
这样,我们可以先将给定的链表连接成环,然后将指定位置断开。
具体代码中,我们首先计算出链表的长度 nn,并找到该链表的末尾节点,将其与头节点相连。这样就得到了闭合为环的链表。然后我们找到新链表的最后一个节点(即原链表的第 (n - 1) - (k mod n)(n−1)−(k mod n) 个节点),将当前闭合为环的链表断开,即可得到我们所需要的结果。
特别地,当链表长度不大于 11,或者 kk 为 nn 的倍数时,新链表将与原链表相同,我们无需进行任何处理。
代码:
class Solution {public:ListNode* rotateRight(ListNode* head, int k) {if (k == 0 || head == nullptr || head->next == nullptr) {return head;}int n = 1;ListNode* iter = head;while (iter->next != nullptr) {iter = iter->next;n++;}int add = n - k % n;if (add == n) {return head;}iter->next = head;while (add--) {iter = iter->next;}ListNode* ret = iter->next;iter->next = nullptr;return ret;}};

