leetcode 61:旋转链表

首先要计算出一共有多少个节点,记为j,然后使用k=k%j

然后使用for循环  每次使得最后一个节点的下一个节点为头节点   倒数第二个节点的下一个节点为NULL

ListNode* rotateRight(ListNode* head, int k) {
    if(head==NULL)
        return NULL;
    if(head->next==NULL)
        return head;
    int j=0;
    ListNode*l2=head;
    while(l2!=NULL){
        j++;
        l2=l2->next;
    }
    for(int i=0;i<k%j;i++){
    ListNode*l1=head;
    ListNode*last=head;
    while(head->next!=NULL){
        last=head;
        head=head->next;
    }
    head->next=l1;
    last->next=NULL;
    }
    return head;
}

猜你喜欢

转载自blog.csdn.net/u013263891/article/details/84504055