Re: [gtk-list] Re: glib: how to sort a doubly linked list?





On Mon, 1 Jun 1998, Eric Wong wrote:

> this ought to do.  One small problem is that the new list has
> an empty element at the beginning (from g_list_alloc()) :(  I
> can't think of a simple workaround.

First I want to say that I'm not sure about any of this.  My application
seems to deal with glist just fine, but I am not sure that I use them
correctly.

That disclaimer aside, I believe that you do _not_ want to do
g_list_alloc().  An empty list is denoted by the NULL pointer.  You should
be able to simply use a NULL pointer.  The insert and delete functions
should work just fine.

One of the things about this, is that you should probably use 

user_data = g_list_insert_sorted( (GList *)user_data, data, &compare_func);

The returned value for g_list_append is the new list.  I would bet that
the returned value of g_list_insert_sorted is the new list. A consequence
of this is that you need to use a double pointer for your user data. 

The following is my changes to your program.  I dropped the print function
and the compare function.  I believe that they should be the same.  Note:
I haven't tried to compile this so I may not have done it correctly.

    void
    sort_glist( gpointer data, gpointer user_data )
    {
+      GList **list = (GList **) user_data;/* For easier to read code. */
      if ( data == NULL ) return;
    
-      g_list_insert_sorted( (GList *)user_data, data, &compare_func );
+      *list = g_list_insert_sorted( *list, data, &compare_func );
    }
    
    int
    main( int argc, char **argv )
    {
-      GList            *glist_old;
-      GList            *glist_new;
+      GList            *glist_old = NULL;
+      GList            *glist_new = NULL;
    
-      glist_old = g_list_alloc();                           /* make list */
-      glist_old->data = "foobar";
+      glist_old = g_list_append( glist_old, "foobar" );

-      g_list_append( glist_old, "joobar" );
-      g_list_append( glist_old, "hoobar" );
-      g_list_append( glist_old, "ioobar" );
-      g_list_append( glist_old, "goobar" );
+      glist_old = g_list_append( glist_old, "joobar" );
+      glist_old = g_list_append( glist_old, "hoobar" );
+      glist_old = g_list_append( glist_old, "ioobar" );
+      glist_old = g_list_append( glist_old, "goobar" );
      g_list_foreach( glist_old, &print_data, NULL );
    
      printf("\n");
    
-      g_list_foreach( glist_old, &sort_glist, glist_new ); /* fill new list */
+      g_list_foreach( &glist_old, &sort_glist, glist_new );/* fill new list */
      g_list_foreach( glist_new, &print_data, NULL );
    
      g_list_free( glist_old );
+      g_list_free( glist_new );
    
      return 0;
    }




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]