天道酬勤巡社,每日記點(diǎn)筆記也是蠻有意思的眠寿。
今天溫習(xí)了下 POINTERS ON C 書中的鏈表一章掏膏,記錄下使用二級(jí)指針對(duì)鏈表進(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;
}
}