首页  >  文章  >  后端开发  >  C语言使用utlist实现的双向链表

C语言使用utlist实现的双向链表

大家讲道理
大家讲道理原创
2016-11-11 13:39:052319浏览

#include 
#include 
#include 
#include "utlist.h"
  
#define BUFLEN 20
  
typedef struct el {
    char bname[BUFLEN];
    struct el *next, *prev;
} el;
  
int namecmp(el *a, el *b) {
    return strcmp(a->bname,b->bname);
}
  
el *head = NULL; /* important- initialize to NULL! */
  
int main(int argc, char *argv[]) {
    el *name, *elt, *tmp, etmp;
  
    char linebuf[BUFLEN];
    int count;
    FILE *file;
  
    if ( (file = fopen( "test11.dat", "r" )) == NULL ) {
        perror("can't open: ");
        exit(-1);
    }
  
    while (fgets(linebuf,BUFLEN,file) != NULL) {
        if ( (name = (el*)malloc(sizeof(el))) == NULL) exit(-1);
        strncpy(name->bname,linebuf,BUFLEN);
        DL_APPEND(head, name);
    }
    DL_SORT(head, namecmp);
    DL_FOREACH(head,elt) printf("%s", elt->bname);
    DL_COUNT(head, elt, count);
    printf("%d number of elements in list\n", count);
  
    memcpy(&etmp.bname, "WES\n", 5);
    DL_SEARCH(head,elt,&etmp,namecmp);
    if (elt) printf("found %s\n", elt->bname);
  
    /* now delete each element, use the safe iterator */
    DL_FOREACH_SAFE(head,elt,tmp) {
      DL_DELETE(head,elt);
    }
  
    fclose(file);
  
    return 0;
}

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn