C語言使用utlist實現的雙向鏈表

bcf2 9年前發布 | 1K 次閱讀 C/C++

utlist 下載地址:https://github.com/troydhanson/uthash

#include <stdio.h>

include <stdlib.h>

include <string.h>

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;

}</pre>

 本文由用戶 bcf2 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!