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(, 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(, sizeof(linklist_t))) == )
return -;
while (ll->next) ll = ll->next;
node->data = data;
node->next = ll->next;
ll->next = node;
return ;
}
return -;
} //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 ;/* Success */
}
}//while
}
return ; /* 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(, sizeof(linklist_t))) == )
return -;
node->data = data;
if (!ll->next) {
ll->next = node;
return ;
}
for (prev=ll,ll=ll->next; ll; prev=ll,ll=ll->next) {
if (cbcomp(data, ll->data) <= ) {
prev->next = node;
node->next = ll;
return ;
}
}
prev->next = node;
}
return ;
} 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. return prev;
  12. }
 
上一篇:jsp动态页面访问报错:HTTP Status 500 - java.lang.NullPointerException,org.apache.jasper.JasperException: java.lang.NullPointerException


下一篇:访问项目时报错org.apache.jasper.JasperException: java.lang.NullPointerException