链表的创建,清空,插入,删除
typedef int (* __compfunc)(const void *, const void *);
//Traverse list. Fast macro to traverse the list.
#define linklist_next(al)
((al) && ((al)=(al)->next) ? (al)->data : NULL)
typedef struct linklist
{
void * data;
struct linklist * next;
} linklist_t;
//Allocate a new list data structure linklist_t * linklist_create() { linklist_t *ll; ll = (linklist_t *) calloc(1, sizeof(linklist_t)); return ll; } //Destroy the list ll. void linklist_destroy(linklist_t *ll) { if (ll) { linklist_t *current = NULL; while ((current=ll)) {ll = ll->next; free(current);} } } //Insert an element at the tail of a list. int linklist_add(linklist_t *ll, void *data) { if (ll) { linklist_t *node = NULL; if ((node=(linklist_t *)calloc(1, sizeof(linklist_t))) == 0) return -1; while (ll->next) ll = ll->next; node->data = data; node->next = ll->next; ll->next = node; return 0; } return -1; } //Remove element from the list. int linklist_remove(linklist_t *ll, void *data) { if (ll) { linklist_t *prev = NULL; while (ll->next) { prev = ll; ll = ll->next; if (ll->data == data) { prev->next = ll->next; free(ll); return 0;/* Success */ } }//while } return 1; /* object not found or NULL list */ } // Do an insertion sort algorithm on the list. An empty list is already // sorted and so is a single element list. int linklist_insert(linklist_t *ll, void *data, __compfunc cbcomp) { if (ll) { linklist_t *node=NULL, *prev=NULL; if (!cbcomp) return linklist_add(ll, data); if ((node=(linklist_t *)calloc(1, sizeof(linklist_t))) == 0) return -1; node->data = data; if (!ll->next) { ll->next = node; return 0; } for (prev=ll,ll=ll->next; ll; prev=ll,ll=ll->next) { if (cbcomp(data, ll->data) <= 0) { prev->next = node; node->next = ll; return 0; } } prev->next = node; } return 0; }
4.链表的逆序
- LinkNode* ReverseLink(LinkNode* head)
- {
- LinkNode *prev=NULL, *next=NULL;
- while(head)
- {
- next = head->next;
- head->next = prev;
- prev = head;
- head = next;
- }
- return prev;
- }