Leetcode 61. 旋转链表

连接旧链表的尾首,找到新链表的尾部即可

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return head;
        ListNode* p=head;
        int L=1;
        while(p->next) ++L,p=p->next;
        p->next=head;
        k%=L;
        L-=k;
        while(--L) head=head->next;
        p=head->next;head->next=NULL;
        return p;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/80234988