2017-10-11 20 views
-1

두의 GList 개체의 빼기 필요 목록의 빼기를 반환하는 글리스트 라이브러리;은 가정 C

g3 = subtract (g1, g2); 
should return 
{"a", "c"); 

g4 = subtract (g2, g1); 
should return 
{"d", "e"); 
+0

숙제입니까? – Jurlie

+0

아니요 집이 아닙니다. –

+0

[Glib - Glist Example in Description] (https://developer.gnome.org/glib/stable/glib-Doubly-Linked-Lists.html)이 유용 할 수 있습니다. –

답변

1
void glist_deep_copy_g_func(gpointer data, gpointer user_data) { 
    GList** result = user_data; 
    if (data) { 
     *result = g_list_append(*result, strdup(data)); 
    } 
    user_data = result; 
} 

GList* glist_deep_copy(GList* source) { 
    GList* result = NULL; 
    g_list_foreach(source, &glist_deep_copy_g_func, &result); 
    return result; 
} 

gint glib_compare_char_ptr(gconstpointer a, gconstpointer b) { 
    return strcmp(a, b); 
} 

GList* glist_subtract(GList* from, GList* by) { 
    GList* result = NULL; 

    if (from && by) { 
     result = glist_deep_copy(from); 
     for (GList *node_from = g_list_first(from); node_from; node_from = 
       g_list_next(node_from)) { 
      for (GList *node_by = g_list_first(by); node_by; node_by = 
        g_list_next(node_by)) { 
       if (!strcmp(node_from->data, node_by->data)) { 
        GList* node = g_list_find_custom(result, node_from->data, 
          &glib_compare_char_ptr); 
        char* data = node->data; 
        result = g_list_remove(result, node->data); 
        free(data); 
       } 
      } 
     } 
    } else if (from) { 
     return glist_deep_copy(from); 
    } 

    return result; 
} 
1

당신은 std::set_difference의 이행을 검토하고 glist을 위해 그것을 적용 할 수 있습니다.

GLib 자체 내에 설정된 차이가 구현되지 않았습니다.

+0

하지만 이것은 C++가 아니라 c를위한 것입니다. –

+0

'적응'이 아니라 '복사 - 붙여 넣기'라고 말했습니다. 아이디어는 그 코드에서 볼 수 있습니다. 구현은 평범한 C와 glist 구조로 다시 작성할 수 있습니다. OP는 C++ 알고리즘의 반복자가 C의 목록 항목에 대한 포인터와 같은 것을 명심해야합니다. – Jurlie