Glib 就是懶.資料處理好手 - GList 雙向鏈結(Doubly-Linked)

許多資深的『慣C』老手,對雙向鏈結串列(Doubly-Linked List)應該並不陌生,這種資料結構被大量地應用在資料記錄,但這對於其他 Scripts Language 或一些高階語言的慣用者來說,卻是一個無法理解的存在,因為對他們來說,動態增減 Array 的數量和內容,是再平常不過且應該要存在的東西。

但對 C 語言卻不是如此,同樣的功能要利用『記憶體的控制技巧(俗稱資料結構)』,才能達成。但由於 GLib 的 GList 整合,使用鏈結串列時,已經不需要再自己對指標(Pointer)做許多低階的處理,這對『慣C』一族和 C 語言的新手來說,毫無疑問地是件好事。

這裡是個使用 GList 的範例,大致說明了基本的操作:
#include <glib.h>

typedef struct {
gchar *name;
gchar *tel;
} ContactNode;

int main() {
GList *contactlist = NULL;
GList *list = NULL;
ContactNode *node;

/* Fred's contact information */
node = (ContactNode *)g_new0(ContactNode, 1);
node->name = g_strdup("Fred Chien");
node->tel = g_strdup("0926333xxx");

/* add the node to the list */
contactlist = g_list_append(contactlist, node);

/* Penx contact information */
node = (ContactNode *)g_new0(ContactNode, 1);
node->name = g_strdup("Penx");
node->tel = g_strdup("09xxxxxxxx");

/* add the node to the list */
contactlist = g_list_append(contactlist, node);

/* print all of list */
for (list=contactlist;list;list=g_list_next(list)) {
node = (ContactNode *)list->data;

printf("Name: %s, Tel:%s\n", node->name, node->tel);
}

/* remove all */
for (list=contactlist;list;list=g_list_next(list)) {
contactlist = g_list_remove(contactlist, list->data);
}

return 0;
}


此外,最近在撰寫一些程式時,用了些奇淫技巧,以列出 GList 最前面 10 筆資料:
for (i=10, list=contactlist;(list) ? i : NULL;list=g_list_next(list), --i) {
node = (ContactNode *)list->data;
printf("Name: %s, Tel:%s\n", node->name, node->tel);
}


GLib 的出現,讓許多人可以丟掉手邊的『資料結構』工具書,真的是很便利呀。 :P

留言

  1. This condition expression:
    list && i
    is, IMO, more straightforward and readable than:
    (list) ? i : NULL

    回覆刪除
  2. Thanks for your nice comment, the condition expression is a general usage correctly. For most of situations, that's a right way to use it.

    BTW, just for my note, I prefer the unusual expression, because it means I can stuff "for()" with more works in the future even if it's not readable.

    回覆刪除
  3. compile時找不到"glib.h"
    應該怎麼安裝呢?
    我是使用Ubuntu

    回覆刪除
  4. 感謝您提供的精簡範例!

    只是有點不大明白,資料應該是有兩筆
    但印出來只有一筆被remove
    {
    contactlist = g_list_remove(contactlist, list->data);
    printf("remove!\n");
    }

    是我哪裡弄錯了嗎? XD

    回覆刪除

張貼留言

這個網誌中的熱門文章

有趣的邏輯問題:是誰在說謊

Web 技術中的 Session 是什麼?

淺談 USB 通訊架構之定義(二)

淺談 USB 通訊架構之定義(一)

Reverse SSH Tunnel 反向打洞實錄