My simple C solution


  • -1
    E
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        if(head->next==NULL && n==1) return NULL;
        struct ListNode *p,*q;
        p->next=head;
        q->next=head;
        int i=0;
        while(i++ < n) q=q->next;
        if(q->next==NULL) {
            return head->next;
        }
        while(q->next!=NULL){
            p=p->next;
            q=q->next;
        }
        p->next=p->next->next;
        return head;
    }

  • 0
    W

    since you neither allocate memory for pointer p, q nor point them to a effective node.
    They are pointing to a unknown space.
    You can not use p->next。。。。


  • 1
    H
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
      struct ListNode Head,*ptr;
      Head.next = head;
      ptr = &Head;
      while(n--)
          head = head -> next;
      while(head)
      {
          head=head->next;
          ptr = ptr->next;
      }
        /*head = ptr ->next;
         free(head);*/
         ptr->next = ptr->next ->next;
         return Head.next;
     }

Log in to reply
 

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