learning-cc4e

Solution to https://cc4e.com/. If you copy these you're not right in the head.
git clone https://kaka.farm/~git/learning-cc4e
Log | Files | Refs

solution.c (1818B)


      1 /* print(lst) */
      2 void pylist_print(struct pylist* self)
      3 {
      4     /* About 10 lines of code
      5        The output should match Python's
      6        list output
      7 
      8        ['Hello world', 'Catch phrase']
      9 
     10         Use printf cleverly, *not* string
     11         concatenation since this is C, not Python.
     12     */
     13   struct lnode *current_node;
     14   printf("[");
     15   for (current_node = self->head;
     16        current_node != NULL;
     17        current_node = current_node->next) {
     18     if (current_node->next != NULL) {
     19       printf("'%s', ", current_node->text);
     20     } else {
     21       printf("'%s'", current_node->text);
     22     }
     23   }
     24   printf("]\n");
     25 }
     26 
     27 /* len(lst) */
     28 int pylist_len(const struct pylist* self)
     29 {
     30     /* One line of code */
     31   struct lnode *current_node = self->head;
     32   int length = 0;
     33   while (current_node != NULL) {
     34     ++length;
     35     current_node = current_node->next;
     36   }
     37 
     38   return length;
     39 }
     40 
     41 /* lst.append("Hello world") */
     42 void pylist_append(struct pylist* self, char *str) {
     43     /* Review: Chapter 6 lectures and assignments */
     44   char *new_str = (
     45     (char *)
     46     malloc(sizeof(char) * (strlen(str) + 1))
     47   );
     48   new_str = strcpy(new_str, str);
     49   struct lnode *new_node = (
     50     (struct lnode *)
     51     malloc(sizeof(struct lnode))
     52   );
     53   new_node->text = new_str;
     54   if (self->head == NULL) {
     55     self->head = new_node;
     56   }
     57   if (self->tail != NULL) {
     58     self->tail->next = new_node;
     59   }
     60   self->tail = new_node;
     61 }
     62 /* lst.index("Hello world") - if not found -1 */
     63 int pylist_index(struct pylist* self, char *str)
     64 {
     65     /* Seven or so lines of code */
     66   struct lnode *current_node = self->head;
     67   int index = 0;
     68 
     69   for (current_node = self->head,
     70        index = 0;
     71        current_node != NULL;
     72        current_node = current_node->next,
     73        ++index) {
     74     if (strcmp(current_node->text, str) == 0) {
     75       return index;
     76     }
     77   }
     78   return -1;
     79 }