当前位置:   article > 正文

C++ | Leetcode C++题解之第61题旋转链表_leecode螺旋链表题解c++

leecode螺旋链表题解c++

题目:

题解:

  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. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/687054
推荐阅读
相关标签
  

闽ICP备14008679号