C Recursive Solution with the help of a Signal


  • 0
    J
    struct Signal{
        int position;           //Indicate the node position.
        struct ListNode* node;  //The node after which is the one we are finding.
    };
    
    struct Signal* find(struct ListNode* node, struct Signal* s, int n){
        if(node->next == NULL) {
            s->position++;      //End of the list, begin to mark the position from the here.
            return s;
        }
        s = find(node->next, s, n);
        if (s->position == n){
            s->node = node;     //The node after which is the one we are finding
        }
        s->position++;
        return s;
    }; 
    
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        //Initialization
        if(head == NULL || n < 1) 
            return head;
        struct Signal p, *s;
        p.position = 0;
         
        //Recersive Finding Process
        s = find(head, &p, n);
        
        //Deleting Process
        if(s->position == n)    //The situation deleting the first one.
            return head->next;
        else
            s->node->next = s->node->next->next;
         return head;
     };

Log in to reply
 

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