C语言面试题分类->链表

链表的创建,清空,插入,删除

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.链表的逆序
  1. LinkNode* ReverseLink(LinkNode* head)  
  2. {  
  3.     LinkNode *prev=NULL, *next=NULL;  
  4.     while(head)  
  5.     {  
  6.         next = head->next;  
  7.         head->next = prev;  
  8.         prev = head;  
  9.         head = next;  
  10.     }  
  11.   
  12.     return prev;  
  13. }  
 
原文地址:https://www.cnblogs.com/mcy0808/p/8883072.html