Easy c++ 6ms one pass


  • 0
    M
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    
            ListNode* prev;
            ListNode* curr;
            ListNode preHead(0);
            preHead.next = head;
            prev = &preHead;
            int j = 0;
            for(int i = 0;i <n-1;i++){
                head = head->next;
            }
            if(head->next == NULL){
                curr = prev->next;
                prev->next = prev->next->next;
                delete curr;
                return preHead.next;
            }
            while(head->next != NULL){
                head = head->next;
                prev = prev->next;
            }
             if(head->next == NULL){
                 curr = prev->next;
                prev->next = curr->next;
                 delete curr;
            }
            return preHead.next;
        }

Log in to reply
 

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