Is the n legal naturally?


  • 0
    J
        struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        int it = 0;
        struct ListNode* prev = head;
        struct ListNode* pivot = head;
        struct ListNode* flag = head;
        for(int i = 0; i < n; i++)
        {
            flag = flag->next;
        }
        if(flag == NULL)
            return head->next;
        while(flag!= NULL)
        {
            if(it != 0)
                prev = prev->next;
            flag = flag->next;
            pivot = pivot->next;
            it++;
        }
        prev->next = pivot->next;
        return head;
    }
    

    I think the below code maybe wrong when n is bigger than the list's length.
    for(int i = 0; i < n; i++)
    {
    flag = flag->next;
    }

    Can anyone answer that?


Log in to reply
 

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