自学内容网 自学内容网

leetcode日记(49)旋转链表

其实不难,就是根据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;
    }
};


原文地址:https://blog.csdn.net/s478527548/article/details/140665486

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!