Created
August 10, 2022 08:55
-
-
Save outlinepix/702770a4ab833220bfc431ae97795a4c to your computer and use it in GitHub Desktop.
python like implementation of list in C language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <assert.h> | |
typedef struct | |
{ | |
char **list; | |
int length; | |
} stringList; | |
void __init__(stringList *list); | |
void append(stringList *list, char *string); | |
void delete (stringList *list, char *string); | |
void print(stringList *list); | |
int main(int argc, char const *argv[]) | |
{ | |
stringList list; | |
__init__(&list); | |
append(&list, "Hello"); | |
append(&list, "World"); | |
append(&list, "!"); | |
delete (&list, "World"); | |
delete (&list, "Hello"); | |
print(&list); | |
return 0; | |
} | |
void __init__(stringList *list) | |
{ | |
list->list = (char **)malloc(sizeof(char *) * 1); | |
list->length = 0; | |
} | |
void append(stringList *list, char *string) | |
{ | |
char *temp_array[list->length + 1]; | |
for (int i = 0; i < list->length; i++) | |
{ | |
temp_array[i] = list->list[i]; | |
} | |
temp_array[list->length] = string; | |
free(list->list); | |
list->list = calloc(list->length + 1, sizeof(char *)); | |
for (int i = 0; i < list->length + 1; i++) | |
{ | |
list->list[i] = temp_array[i]; | |
} | |
list->length++; | |
} | |
void delete (stringList *list, char *string) | |
{ | |
char *temp_array[list->length]; | |
int found = 0; | |
for (int i = 0; i < list->length; i++) | |
{ | |
if (strcmp(list->list[i], string) != 0) | |
{ | |
temp_array[i] = list->list[i]; | |
} | |
else | |
{ | |
found = 1; | |
} | |
} | |
if (found) | |
{ | |
free(list->list); | |
list->list = calloc(list->length - 1, sizeof(char *)); | |
for (int i = 0; i < list->length - 1; i++) | |
{ | |
list->list[i] = temp_array[i]; | |
} | |
list->length--; | |
} | |
} | |
void print(stringList *list) | |
{ | |
for (int i = 0; i < list->length; i++) | |
{ | |
printf("%s\n", list->list[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment