Very short c code in 8ms


  • 1
    5
     typedef struct ListNode ListNode;
    struct ListNode* removeElements(struct ListNode* head, int val) {
        ListNode* dummy = (ListNode*)malloc(sizeof(ListNode));
        dummy->next = head;
        ListNode* p = dummy;
        while( NULL != p->next){
            if( val == p->next->val ) p->next = p->next->next;
            else p = p->next;
        }
        return dummy->next;
    }

  • 0
    X

    /**

    • Definition for singly-linked list.
    • struct ListNode {
    • int val;
      
    • struct ListNode *next;
      
    • };
      /
      struct ListNode
      removeElements(struct ListNode* head, int val) {
      struct ListNode *p = head;
      struct ListNode *q;
      while(p)
      {
      q = p->next;
      if(q && q->data==val)
      {
      p->next = q->next;
      free(q);
      return p;
      }
      p = q;
      }

    }


  • 0
    M

    Clever! Adding a dummy Node at the beginning makes the loop uniform and thus elegant.


  • 0
    Q

    cool, just notice memory leak :)


  • 0
    A

    You miss struct keyword and forget to free the pointer.


  • 0
    A

    I wrote the similar code, but it still costs 12ms!


  • 0
    5

    i have use typedef before so i miss struct , and I should add the free process ,you r right


  • 0
    5

    yes ,adding the free process makes better!


  • 0
    A

    OK, I do not notice that there is typedef, however, I copy your code and run, it costs 12ms, not 8ms.


  • 0
    A

    I think it may be because of the update of the compiler.


  • 0
    5

    typedef struct ListNode ListNode;
    struct ListNode* removeElements(struct ListNode* head, int val) {
    ListNode dummy ;
    dummy.next = head;
    ListNode* p = &dummy;
    while( NULL != p->next){
    if( val == p->next->val ) p->next = p->next->next;
    else p = p->next;
    }
    return dummy.next;
    }


  • 0
    5

    bellow is better and use local valiable dummy ,but it costs 12ms ,how to get 8ms?

    typedef struct ListNode ListNode;
    struct ListNode* removeElements(struct ListNode* head, int val) {
    ListNode dummy ;
    dummy.next = head;
    ListNode* p = &dummy;
    while( NULL != p->next){
    if( val == p->next->val ) p->next = p->next->next;
    else p = p->next;
    }
    return dummy.next;
    }


Log in to reply
 

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