题目:


image.png


个人解答:

递归方法解答。注意测试用例中有k值超过链表数量,此时应当取k%链表数量来减少循环。

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. ListNode* rotateRight(ListNode* head, int k) {
  14. if(!head||!head->next||k==0)
  15. return head;
  16. ListNode* dummy = new ListNode(0,head);
  17. int count_total = 0;
  18. while(head)
  19. {
  20. head=head->next;
  21. count_total++;
  22. }
  23. head = dummy->next;
  24. k = k % count_total;
  25. if(k==0||k=count_total)
  26. return head;
  27. if(k==1)
  28. {
  29. int value_n = head->val, value_nn = 0;
  30. int temp = 0;
  31. while(head->next->next)
  32. {
  33. temp = value_n;
  34. value_n = head->next->val;
  35. value_nn = head->next->next->val;
  36. head->next->val = temp;
  37. head = head->next;
  38. }
  39. if(!dummy->next->next->next)
  40. {
  41. dummy->next->val = head->next->val;
  42. dummy->next->next->val = value_n;
  43. }
  44. else
  45. {
  46. head->next->val = value_n;
  47. dummy->next->val = value_nn;
  48. }
  49. return dummy->next;
  50. }
  51. else
  52. {
  53. head = rotateRight(rotateRight(head,k-1),1);
  54. }
  55. return head;
  56. }
  57. };

官方解答:

思路:

这样,我们可以先将给定的链表连接成环,然后将指定位置断开。

具体代码中,我们首先计算出链表的长度 nn,并找到该链表的末尾节点,将其与头节点相连。这样就得到了闭合为环的链表。然后我们找到新链表的最后一个节点(即原链表的第 (n - 1) - (k mod n)(n−1)−(k mod n) 个节点),将当前闭合为环的链表断开,即可得到我们所需要的结果。

特别地,当链表长度不大于 11,或者 kk 为 nn 的倍数时,新链表将与原链表相同,我们无需进行任何处理。

代码:

  1. class Solution {
  2. public:
  3. ListNode* rotateRight(ListNode* head, int k) {
  4. if (k == 0 || head == nullptr || head->next == nullptr) {
  5. return head;
  6. }
  7. int n = 1;
  8. ListNode* iter = head;
  9. while (iter->next != nullptr) {
  10. iter = iter->next;
  11. n++;
  12. }
  13. int add = n - k % n;
  14. if (add == n) {
  15. return head;
  16. }
  17. iter->next = head;
  18. while (add--) {
  19. iter = iter->next;
  20. }
  21. ListNode* ret = iter->next;
  22. iter->next = nullptr;
  23. return ret;
  24. }
  25. };

image.png