My 4ms C code sharing


  • 0
    Z
    struct ListNode* rotateRight(struct ListNode* head, int k) {
    if (!(head) || !(head->next)) return head;
    struct ListNode *p, *temp;
    int len=0;
    p=head;
    while (p){
        temp=p;
        len++;
        p=p->next;
    }
    if ((k%len==0) && (k>=len)) return head;
    temp->next=head;//make the list as a circle//
    p=head;
    if (k<len){ 
        for (int i=1; i<len-k; i++){
            p=p->next;
        }
        head=p->next;
        p->next=NULL;
    }else{
        int j=k%len;
        for (int i=1; i<len-j; i++){
            p=p->next;
        }
        head=p->next;
        p->next=NULL;
    }//find the right position to break the circle//
    return head;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.