[C語言]利用二級(jí)指針進(jìn)行鏈表的添加和刪除處理

天道酬勤,每日記點(diǎn)筆記也是蠻有意思的。

今天溫習(xí)了下 POINTERS ON C 書中的鏈表一章,記錄下使用二級(jí)指針對鏈表進(jìn)行添加和刪除處理。

插入函數(shù):


#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;
}

刪除函數(shù):



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;
      }
  }
}

不過注意到 寫法一 中重復(fù)比較多,例如curr 其實(shí)都沒必要存在!所以我更推薦寫法二。

// 寫法二:
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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容