美文网首页
[C语言]利用二级指针进行链表的添加和删除处理

[C语言]利用二级指针进行链表的添加和删除处理

作者: NinthDay | 来源:发表于2015-12-25 22:36 被阅读304次

    天道酬勤,每日记点笔记也是蛮有意思的。

    今天温习了下 POINTERS ON C 书中的链表一章,记录下使用二级指针对链表进行添加和删除处理。

    插入函数:

    
    #define TRUE 1
    #define FALSE 0
    /*
      * brief: Single Linked List
      * para:   head       -> the head of list
      *           newValue -> item which to be inserted
    */
    int sll_insert(node **head,int newValue)
    {
      node * curr;
      node *new;
    
      // find the position
      while((curr = *head)  != NULL && curry->value <newValue)
               head = &curr->next;
     
      // new
      new = (node *)malloc(sizeof(node));
      if(new == NULL)return FALSE;
     
      //insert
      new->value = newValue;
      new->next = curr;
    
      *head = new;
      return TRUE;
    }
    

    删除函数:

    
    
    typedefbool(* remove_fn)(node const* v);   
    
    
    // 写法一:
    void remove_if(node ** head, remove_fn rm)
    {
      node *curr;
      
       while( (curr = *head) != NULL)
      {
          // notice entry and curr point both point to the same one
          node *entry = curr;//delete it !!
          if(rm(entry)){
             *head = curr->next;   
             free(entry);
          }else{
            head = &curr->next;
          }
      }
    }
    

    不过注意到 写法一 中重复比较多,例如curr 其实都没必要存在!所以我更推荐写法二。

    // 写法二:
    void remove_if(node ** head, remove_fn rm)
    {
        for(node** curr = head; *curr; )
        {
            node * entry = *curr;
            if(rm(entry))
            {
                *curr = entry->next;
                free(entry);
            }
            else
                curr = &entry->next;
        }
    }
    

    相关文章

      网友评论

          本文标题:[C语言]利用二级指针进行链表的添加和删除处理

          本文链接:https://www.haomeiwen.com/subject/hvfbhttx.html