@@ -334,3 +334,76 @@ void list_mapDelete(List_t *l, void *(*f) (void *)) {
334
334
node = node -> next ;
335
335
}
336
336
}
337
+
338
+ void list_sort (List_t * l ) {
339
+ if (!l -> compare ) {
340
+ fprintf (stderr , "Error: no compare function defined. Cannot sort.\n" );
341
+ return ;
342
+ }
343
+ if (!l -> elem_size ) {
344
+ fprintf (stderr , "Error: element size is not defined. Cannot sort.\n" );
345
+ return ;
346
+ }
347
+ if (l -> size > 0 ) {
348
+ /* copy all elements into an array */
349
+ void * * arr = calloc (l -> size , sizeof (void * ));
350
+ ListNode_t * node = l -> front ;
351
+ size_t idx = 0 ;
352
+ while (node ) {
353
+ ListNode_t * next = node -> next ;
354
+ arr [idx ++ ] = node -> data ;
355
+ list_removeNode (l , node ); /* frees the node, not the data*/
356
+ node = next ;
357
+ }
358
+
359
+ assert (l -> size == 0 && "List is not empty for some reason" );
360
+ /* use quicksort to sort the array */
361
+ qsort (arr , l -> size , l -> elem_size , l -> compare );
362
+
363
+ /* copy the elements back */
364
+ for (idx = 0 ; idx < l -> size ; ++ idx ) {
365
+ list_addBack (l , arr [idx ]);
366
+ }
367
+ }
368
+ }
369
+
370
+ List_t list_union (List_t * l1 , List_t * l2 ) {
371
+ if (!l1 -> copy || !l2 -> copy ) {
372
+ fprintf (stderr , "Error: copy function not defined. Can't perform union\n" );
373
+ exit (1 );
374
+ }
375
+ if (!l1 -> compare || (l1 -> compare != l2 -> compare )) {
376
+ fprintf (stderr , "Error: compare not defined, or not the same comparison"
377
+ "function. Can't perform union\n" );
378
+ exit (1 );
379
+ } else if (l1 -> size == 0 ) {
380
+ return list_deepCopy (l2 );
381
+ } else if (l2 -> size == 0 ) {
382
+ return list_deepCopy (l1 );
383
+ } else {
384
+ List_t res ;
385
+ list_init (& res , l1 -> del ? l1 -> del : l2 -> del );
386
+ }
387
+ }
388
+
389
+ List_t list_deepCopy (List_t * l ) {
390
+ if (!l -> copy ) {
391
+ fprintf (stderr , "Error: no copy function defined. Can't deepCopy\n" );
392
+ exit (1 );
393
+ } else {
394
+ List_t res ;
395
+ ListNode_t * node = l -> front ;
396
+ list_init (& res , l -> del );
397
+ res .copy = l -> copy ;
398
+ res .toString = l -> toString ;
399
+ res .print = l -> print ;
400
+ res .elem_size = l -> elem_size ;
401
+ res .name = l -> name ;
402
+ while (node ) {
403
+ list_addBack (& res , l -> copy (node -> data ));
404
+ node = node -> next ;
405
+ }
406
+ assert (res .size == l -> size && "Sizes don't match for some reason" );
407
+ return res ;
408
+ }
409
+ }
0 commit comments