麻花痒 发表于 2024-7-30 02:02:37

leetcode日记(49)旋转链表

https://i-blog.csdnimg.cn/direct/adbf27f858a144629f0a13d6dadc2306.png
其实不难,就是根据k=k%len判断需要旋转的位置,再将后半段接在前半段前面就行。
/**
* 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==NULL||k==0) return head;
      ListNode* h=head;
      int len=1;
      while(h->next) {h=h->next;len++;}
      k=k%len;
      if(k==0) return head;
      ListNode* e=head;
      for(int i=0;i<len-k-1;i++) e=e->next;
      ListNode* n=e->next;
      e->next=NULL;
      h->next=head;
      return n;
    }
};

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: leetcode日记(49)旋转链表