My short 0ms c solution


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     *
     * example :
     * 1->2->3, n = 1, remove 3
     * |1 -> |2 -> |3 -> |null |
     * |del  |end  |     |     |
     * |     |del  |end  |     |
     * |     |     |del  |end  |
     * 1->2->3, n = 2, remove 2
     * |1 -> |2 -> |3 -> |null |
     * |del  |     |end  |     |
     * |     |del  |     |end  |
     * 1->2->3, n = 3, remove 1
     * |1 -> |2 -> |3 -> |null |
     * |del  |     |     |end  |
     */
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    	if (head == NULL) return NULL;
    	struct ListNode **del = &head, *end = head;
    	while (--n >= 0 && end != NULL) { end = end->next; }
    	while (end) {
    		end = end->next;
    		del = &((*del)->next);
    	}
    	if (*del == head) return head->next;
    	else {
    		*del = (*del)->next;
    		return head;
    	}
    }

  • 0
    F

    here is mine

    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode* fast=head;
    struct ListNode* slow=head;
    int count=0;
    while(count<n){
        fast=fast->next;
        count++;
    }
    if(fast!=NULL){
     while(fast->next!=NULL){
        fast=fast->next;
        slow=slow->next;
        }
        slow->next=slow->next->next;
         return head;
    }
    else
        return head->next;
    

    }


Log in to reply
 

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