Rewrite to use LinkedList instead of Vector

This commit is contained in:
Stephen Seo 2020-06-06 20:36:04 +09:00
parent c05df15890
commit 8d553f54d9

View file

@ -2,72 +2,92 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
typedef struct SimpleVector { typedef struct Node {
char *data; struct Node* next;
unsigned int capacity; char value;
unsigned int size; } Node;
} SimpleVector;
SimpleVector sv_init(unsigned int capacity) { void n_push(Node **node, char value) {
SimpleVector sv; if(*node) {
memset(&sv, 0, sizeof(SimpleVector)); Node *current = *node;
if(current->next) {
sv.data = (char*)malloc(capacity * sizeof(char)); n_push(&current->next, value);
sv.capacity = capacity; } else {
current->next = (Node*)malloc(sizeof(Node));
return sv; memset(current->next, 0, sizeof(Node));
} current->next->value = value;
void sv_push(SimpleVector *sv, char value) {
if(!sv->data || sv->capacity == 0) {
return;
} else if(sv->size == sv->capacity) {
char *new_data = (char*)malloc(sv->capacity * 2 * sizeof(char));
memcpy(new_data, sv->data, sizeof(char) * sv->size);
free(sv->data);
sv->data = new_data;
sv->capacity *= 2;
} }
} else {
sv->data[sv->size++] = value; *node = (Node*)malloc(sizeof(Node));
} memset(*node, 0, sizeof(Node));
(*node)->value = value;
void sv_cleanup(SimpleVector sv) {
if(sv.data) {
free(sv.data);
} }
} }
void sv_print(SimpleVector sv) { Node* list_from_input(int argc, char **argv) {
for(unsigned int i = 0; i < sv.size; ++i) { Node *head = NULL;
printf("%c ", sv.data[i]);
}
printf("\n");
}
void sv_print_rotations(SimpleVector sv) {
for(unsigned int i = 0; i < sv.size; ++i) {
printf(" ");
for(unsigned int j = i; j < i + sv.size; ++j) {
printf("%c ", sv.data[j % sv.size]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
SimpleVector sv = sv_init(32);
--argc; ++argv; --argc; ++argv;
while(argc > 0) { while(argc > 0) {
sv_push(&sv, argv[0][0]); n_push(&head, argv[0][0]);
--argc; ++argv; --argc; ++argv;
} }
printf("Got vector: ");
sv_print(sv);
printf("Rotations:\n");
sv_print_rotations(sv);
sv_cleanup(sv); return head;
}
void cleanup_list(Node *node) {
if(node) {
if(node->next) {
cleanup_list(node->next);
}
free(node);
}
}
void n_print(Node *node) {
printf("%c ", node->value);
if(node->next) {
n_print(node->next);
}
}
void n_print_until(Node *current, Node *end) {
printf("%c ", current->value);
if(current->next && current->next != end) {
n_print_until(current->next, end);
}
}
void n_print_rotations(Node *node) {
Node *start = node;
while(node) {
printf(" ");
n_print(node);
if(start != node) {
n_print_until(start, node);
}
printf("\n");
node = node->next;
}
printf("\n");
}
int main(int argc, char **argv) {
Node *list = list_from_input(argc, argv);
if(!list) {
printf("List is empty\n");
cleanup_list(list);
return 1;
}
printf("Got list: ");
n_print(list);
printf("\nRotations:\n");
n_print_rotations(list);
cleanup_list(list);
return 0; return 0;
} }