Homework 07: list.c

This commit is contained in:
Owen Dorweiler 2025-03-29 17:05:36 -04:00
commit dfbd984e0a

View file

@ -10,8 +10,12 @@
* @return Pointer to new List structure (must be deleted later). * @return Pointer to new List structure (must be deleted later).
**/ **/
List * list_create() { List * list_create() {
// TODO List *newList = calloc(1, sizeof(List)); // Use calloc to set everything to 0
return NULL;
newList->sentinel.next = &newList->sentinel;
newList->sentinel.prev = &newList->sentinel;
return newList;
} }
/** /**
@ -21,7 +25,15 @@ List * list_create() {
* @param release Whether or not to release the string values. * @param release Whether or not to release the string values.
**/ **/
void list_delete(List *l, bool release) { void list_delete(List *l, bool release) {
// TODO Node *current = l->sentinel.next; // Start with first node after sentinel node
while (current != &l->sentinel) {
Node *next = current->next;
node_delete(current, release); // Call node_delete and pass in release variable
current = next;
}
free(l);
} }
/** /**
@ -31,7 +43,11 @@ void list_delete(List *l, bool release) {
* @param v Value to add to back of List structure. * @param v Value to add to back of List structure.
**/ **/
void list_append(List *l, Value v) { void list_append(List *l, Value v) {
// TODO Node *appNode = node_create(v, &l->sentinel, l->sentinel.prev);
l->sentinel.prev->next = appNode;
l->sentinel.prev = appNode;
l->size++;
} }
/** /**
@ -42,9 +58,26 @@ void list_append(List *l, Value v) {
* *
* @return Value at index in List structure (-1 if index is out of bounds). * @return Value at index in List structure (-1 if index is out of bounds).
**/ **/
Value list_pop(List *l, size_t index) { Value list_pop(List *l, size_t index) {
// TODO if (index >= l->size) {
return (Value)-1L; return (Value)-1L;
}
// Find the node based on index
Node *current = l->sentinel.next;
for (size_t i = 0; i < index; i++) {
current = current->next;
}
// Unlink the node
current->prev->next = current->next;
current->next->prev = current->prev;
Value v = current->value;
node_delete(current, false);
l->size--;
return v;
} }
/* vim: set sts=4 sw=4 ts=8 expandtab ft=c: */ /* vim: set sts=4 sw=4 ts=8 expandtab ft=c: */