Advertisement
cd62131

sort list

Jul 10th, 2014
416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct cell_t cell_t;
  4. struct cell_t {
  5.   int key;
  6.   cell_t *next;
  7. };
  8. typedef struct {
  9.   int key;
  10. } node_t;
  11. cell_t *new_cell(int key) {
  12.   cell_t *new = (cell_t *) malloc(sizeof(cell_t));
  13.   new->key = key;
  14.   new->next = NULL;
  15.   return new;
  16. }
  17. cell_t *add_cell(cell_t *first, int key) {
  18.   cell_t *p, *prev, *new = new_cell(key);
  19.   for (p = first, prev = NULL; p; prev = p, p = p->next)
  20.     if (p->key > key) break;
  21.   if (!p && !prev) {
  22.     return new;
  23.   } else if (!p && prev) {
  24.     prev->next = new;
  25.     return first;
  26.   } else if (p && !prev) {
  27.     new->next = p;
  28.     return new;
  29.   } else {
  30.     prev->next = new;
  31.     new->next = p;
  32.     return first;
  33.   }
  34. }
  35. void puts_cell(cell_t *first) {
  36.   cell_t *p;
  37.   printf("[");
  38.   for (p = first; p; p = p->next) {
  39.     printf("%d", p->key);
  40.     if (p->next) printf(", ");
  41.   }
  42.   printf("]\n");
  43. }
  44. node_t *new_node(int key) {
  45.   node_t *new = (node_t *) malloc(sizeof(node_t));
  46.   new->key = key;
  47.   return new;
  48. }
  49. node_t **add_node(node_t **prime, int key, int *count) {
  50.   node_t *new = new_node(key);
  51.   prime = realloc(prime, ++(*count) * sizeof(node_t *));
  52.   prime[*count - 1] = new;
  53.   return prime;
  54. }
  55. void puts_node(node_t **prime, int count) {
  56.   int i;
  57.   printf("[");
  58.   for (i = 0; i < count; i++) {
  59.     printf("%d", prime[i]->key);
  60.     if (i < count - 1) printf(", ");
  61.   }
  62.   printf("]\n");
  63. }
  64. int compare_node(const void *p1, const void *p2) {
  65.   node_t **q1 = (node_t **) p1;
  66.   node_t **q2 = (node_t **) p2;
  67.   return (*q1)->key - (*q2)->key;
  68. }
  69. int main(void) {
  70.   int a[] = { 19, 15, 18, 2, 6, 12, 19, 26, 5, 20 };
  71.   int i;
  72.   cell_t *first = NULL;
  73.   node_t **prime = NULL;
  74.   int count = 0;
  75.   puts("Cell");
  76.   for (i = 0; i < sizeof(a) / sizeof(int); i++) {
  77.     first = add_cell(first, a[i]);
  78.     puts_cell(first);
  79.   }
  80.   puts("Node");
  81.   for (i = 0; i < sizeof(a) / sizeof(int); i++) {
  82.     prime = add_node(prime, a[i], &count);
  83.     puts_node(prime, count);
  84.   }
  85.   puts("sort");
  86.   qsort(prime, count, sizeof(node_t *), compare_node);
  87.   puts_node(prime, count);
  88.   return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement