| glib學(xué)習筆記 2 使用glib提供的鏈表 轉載請注明出處,或聯(lián)系 fanyuanmail@126.com 在寫(xiě)程序中經(jīng)常會(huì )用到一些對鏈表的操作,很多時(shí)候自己維護一套函數。其實(shí)在glib中有一個(gè)現成的list可以使用 Doubly-Linked Lists - linked lists containing integer values or pointers to data, with the ability to iterate over the list in both directions Singly-Linked Lists - linked lists containing integer values or pointers to data, limited to iterating over the list in one direction
glib提供了一個(gè)雙向鏈表和一個(gè)單向鏈表。下面這個(gè)例子是對鏈表進(jìn)行追加,然后逆序,使用起來(lái)非常簡(jiǎn)單,現在越來(lái)越喜歡這個(gè)庫了。
1.首先對鏈表增加了三個(gè)node 2.遍歷整個(gè)鏈表 3.對鏈表逆序 4.遍歷整個(gè)鏈表
1 #include <glib.h> 2 int count=0; 3 4 void print_data(char* data) 5 { 6 count++; 7 printf("count %d\n data is %s\n",count,data); 8 } 9 10 int main(int argc, char *argv[]) 11 { 12 GList* list=NULL; 13 GList* newlist; 14 list=g_list_append(list, "first"); 15 list=g_list_append(list, "second"); 16 list=g_list_append(list, "third"); //print_data要求傳遞一個(gè)函數 17 g_list_foreach(list,print_data,list->data); 18 g_printf("reverse the list\n"); 19 newlist=g_list_reverse(list); 20 g_list_foreach(newlist,print_data,newlist->data); 21 return 0; 22 }
執行結果 [root@dhcp-cbjs05-218-247 glib_study]# ./glist_test count 1 data is first count 2 data is second count 3 data is third reverse the list count 4 data is third count 5 data is second count 6 data is first |