My c solution 4ms


  • 0
    B
    struct ListNode* rotateRight(struct ListNode* head, int k) {
        if (k == 0 || head == NULL) return head;
        struct ListNode *p1 = head;
        struct ListNode *p2 = head;
        int len = 0;
        while (k--) {
            if (p2->next) {
                ++len;
                p2 = p2->next;
            }
            else { // if p2->next reach the tail, we can know the length of this link. And then get the mod of k, and make p2 starts from the head
                k %= (len + 1);
                p2 = head;
            }
        }
        while (p2->next) {
            p2 = p2->next;
            p1 = p1->next;
        }
        p2->next = head;
        head = p1->next;
        p1->next = NULL;
        return head;
    }

Log in to reply
 

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