http://wordaligned.org/articles/two-star-programming
http://coolshell.cn/articles/8990.html/comment-page-2
重点在于core low-level coding,其实我们平时不需要考虑这么多,以普遍的方法实现健壮的功能就可以了,不过既然知道了有这么回事,还是把它想清楚吧,事情的本质就是指针存储的是地址,一个巧妙的应用而已。
注意:代码中没有free掉remove的节点
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define RM_FUN_OLD 0
typedef struct _LIST_ITEM
{
int nItemValue;
struct _LIST_ITEM *ptNext;
}ListItem;
ListItem *NewList(int n)
{
ListItem *ptNew = NULL;
ListItem *ptLast = NULL;
int i = 0;
for(i = 0; i < n; i++)
{
ListItem *ptCur = (ListItem *)calloc(1, sizeof(ListItem));
ptCur->nItemValue = i;
if(NULL == ptNew)
{
ptNew = ptLast = ptCur;
}
else
{
ptLast->ptNext = ptCur;
ptLast = ptCur;
}
}
return ptNew;
}
void PrintList(ListItem *ptList)
{
printf("List:");
while(ptList)
{
printf("%d ", ptList->nItemValue);
ptList = ptList->ptNext;
}
printf("\r\n");
}
#if RM_FUN_OLD
ListItem *DoRemove(ListItem *ptList, int (*fn_remove)(ListItem *ptItem))
{
ListItem *ptNewHead = ptList;
ListItem *ptPre = NULL;
while(ptList)
{
if(0 == fn_remove(ptList))
{
if(ptPre == NULL)
{
ptNewHead = ptList->ptNext;
}
else
{
ptPre->ptNext = ptList->ptNext;
}
}
else
{
ptPre = ptList;
}
ptList = ptList->ptNext;
}
return ptNewHead;
}
#else
void DoRemove(ListItem **ptList, int (*fn_remove)(ListItem *ptItem))
{
ListItem **curr = ptList;
while (*curr)
{
ListItem *entry = *curr;
if (0 == fn_remove(entry))
{
*curr = entry->ptNext;
}
else
{
curr = &entry->ptNext;
}
}
}
#endif
int fn_remove_item(ListItem *ptItem)
{
if(ptItem->nItemValue != 3)
return 0;
return 1;
}
int main(void)
{
ListItem *ptList = NewList(10);
PrintList(ptList);
#if RM_FUN_OLD
ptList = DoRemove(ptList, fn_remove_item);
#else
DoRemove(&ptList, fn_remove_item);
#endif
PrintList(ptList);
return 0;
}