aboutsummaryrefslogtreecommitdiff
path: root/src/lib/list.c
diff options
context:
space:
mode:
authorBlake Romero <blake@developercraft.com>2025-10-13 23:21:54 +0100
committerBlake Romero <blake@developercraft.com>2025-10-13 23:23:43 +0100
commit3a6d7fdfcfe7fe1fa1c09788287e1b005a85a71e (patch)
tree8385aac5907216014d68fd1bbfd9c8089804807e /src/lib/list.c
parent2a763f9016f35dfc17099d7d8f258266b6b7dd62 (diff)
Updated list tests & refactored code
Diffstat (limited to 'src/lib/list.c')
-rw-r--r--src/lib/list.c43
1 files changed, 26 insertions, 17 deletions
diff --git a/src/lib/list.c b/src/lib/list.c
index 26c8cc1..a0357e9 100644
--- a/src/lib/list.c
+++ b/src/lib/list.c
@@ -15,6 +15,10 @@ Node* node_init(int value) {
}
void list_print(Node* head) {
+ if (head == NULL) {
+ puts("list is NULL");
+ return;
+ }
Node* node = head;
printf("[ ");
while (node != NULL) {
@@ -22,7 +26,6 @@ void list_print(Node* head) {
node = node->next;
}
printf("]\n");
- free(node);
}
void list_vprint(Node* head) {
@@ -32,7 +35,25 @@ void list_vprint(Node* head) {
node = node->next;
printf(" |\n");
}
- printf("[/] %s\n", (char*) node);
+ printf("[/] %s\n", (char *)node);
+}
+
+int list_get(Node* n, int index) {
+ Node* m = n;
+ if (index > list_length(n)-1) return -1;
+ for (int i=0; i<index ; ++i) m = m->next;
+ return m->value;
+}
+
+void list_set(Node* n, int index, int value) {
+ if (index > list_length(n)) {
+ puts("Error: Setting list out of bounds");
+ return;
+ }
+ Node *m = n;
+ for (int i=0; i<index ; ++i)
+ m = n->next;
+ m->value = value;
}
int list_length(Node* head) {
@@ -54,8 +75,8 @@ int list_pop(Node** head) {
return val;
}
-void list_append(Node* head, int value) {
- Node* n = head;
+void list_append(Node** head, int value) {
+ Node* n = *head;
while (n->next != NULL) n = n->next;
n->next = node_init(value);
}
@@ -77,25 +98,13 @@ void list_insert(Node** head, int value, int index) {
void list_free(Node** head) {
while (*head != NULL) {
Node* n = *head;
+ n->value=0;
*head = (*head)->next;
free(n);
}
*head = NULL;
}
-int list_rmlast(Node** head) {
- Node* n = *head;
- Node* cur = NULL;
- while (n->next != NULL) {
- cur = n;
- n = n->next;
- }
- int val = n->value;
- cur->next = NULL;
- free(n);
- return val;
-}
-
int list_rm(Node** head, int index) {
Node* n = *head;
Node* cur = NULL;