127 lines
2.8 KiB
C
127 lines
2.8 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include "llist.h"
|
|
|
|
void ll_init(linked_list* list) {
|
|
list->head = NULL;
|
|
}
|
|
|
|
// Function to create a new node
|
|
advent_node* ll_create_node(advent_map map) {
|
|
advent_node* new_node = (advent_node*)malloc(sizeof(advent_node));
|
|
if (new_node != NULL) {
|
|
new_node->map = map;
|
|
new_node->next = NULL;
|
|
}
|
|
return new_node;
|
|
}
|
|
|
|
// Function to add a node to the beginning of the list
|
|
void ll_prepend(linked_list* list, advent_map map) {
|
|
advent_node* new_node = ll_create_node(map);
|
|
if (new_node != NULL) {
|
|
new_node->next = list->head;
|
|
list->head = new_node;
|
|
}
|
|
}
|
|
|
|
// Function to add a node to the end of the list
|
|
void ll_append(linked_list* list, advent_map map) {
|
|
advent_node* newNode = ll_create_node(map);
|
|
if (newNode != NULL) {
|
|
if (list->head == NULL) {
|
|
list->head = newNode;
|
|
} else {
|
|
advent_node* current = list->head;
|
|
while (current->next != NULL) {
|
|
current = current->next;
|
|
}
|
|
current->next = newNode;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Function to remove a node with a given value
|
|
void ll_remove(linked_list* list, advent_map map) {
|
|
advent_node* current = list->head;
|
|
advent_node* prev = NULL;
|
|
|
|
while (current != NULL && !ADVENT_MAP_EQ(current->map, map)) {
|
|
prev = current;
|
|
current = current->next;
|
|
}
|
|
|
|
if (current != NULL) {
|
|
if (prev != NULL) {
|
|
prev->next = current->next;
|
|
} else {
|
|
list->head = current->next;
|
|
}
|
|
free(current);
|
|
}
|
|
}
|
|
|
|
// Function to print the linked list
|
|
void ll_print(linked_list* list) {
|
|
advent_node* current = list->head;
|
|
while (current != NULL) {
|
|
ADVENT_MAP_PRINT(current->map);
|
|
current = current->next;
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
// Function to free the memory used by the linked list
|
|
void ll_free(linked_list* list) {
|
|
advent_node* current = list->head;
|
|
advent_node* next;
|
|
|
|
while (current != NULL) {
|
|
next = current->next;
|
|
free(current);
|
|
current = next;
|
|
}
|
|
|
|
list->head = NULL;
|
|
}
|
|
|
|
#if 0
|
|
|
|
// Example usage
|
|
int main() {
|
|
linked_list myList;
|
|
ll_init(&myList);
|
|
|
|
advent_map map1;
|
|
map1.dest = 1;
|
|
map1.src = 50;
|
|
map1.len = 5;
|
|
|
|
advent_map map2;
|
|
map2.dest = 60;
|
|
map2.src = 500;
|
|
map2.len = 2;
|
|
|
|
advent_map map3;
|
|
map3.dest = 800;
|
|
map3.src = 8000;
|
|
map3.len = 5;
|
|
|
|
ll_append(&myList, map1);
|
|
ll_append(&myList, map2);
|
|
ll_append(&myList, map3);
|
|
|
|
printf("Original List: \n");
|
|
ll_print(&myList);
|
|
|
|
ll_remove(&myList, map2);
|
|
|
|
printf("List after removing 2: \n");
|
|
ll_print(&myList);
|
|
|
|
ll_free(&myList);
|
|
|
|
return 0;
|
|
}
|
|
|
|
#endif
|