C simple one pass solution


  • 4
    H
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        struct ListNode* firstNode = head;
        struct ListNode* nstepNode = head;
        struct ListNode* prevNode = NULL;
        
        while(n-- > 0 && nstepNode != NULL) {
            nstepNode = nstepNode->next;
        }
        
        while(nstepNode != NULL) {
            prevNode = firstNode;
            firstNode = firstNode->next;
            nstepNode = nstepNode->next;
        }
        
        if(prevNode == NULL) {
            head = head->next;
        }
        else {
            prevNode->next = firstNode->next;
        }
        
        return head;
    }

  • 3
    L
      .....
      struct ListNode* temp = NULL;
      if(prevNode == NULL) {
            temp = head;
            head = head->next;
      }
      else {
            temp = firstNode;
            prevNode->next = firstNode->next;
            
       }
       free(temp);
       .....
    

  • 0
    M

    You have to free the node.


  • 0
    H

    Correct! Thanks for reminding.


Log in to reply
 

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