I needed a sorted-list that I can iterate over to render elements in layers. Right now, delete_item
deletes the first node with a matching priority it finds but I intend to delete specific list items in my implementation.
I didn't know if I needed the list to be doubly linked, but it turns out it makes deleting an item from the list easier. I've also seen people initializing the memory with calloc
, is it important in this case?
There's also probably a way to give each list item a unique identifier (apart from its pointer) so that I can delete a specific item instead of deleting the first occurrence. For now, I'll just use the pointer...
Also, what do you think of my self-compiling trick?
//usr/bin/gcc ${0##*/} -o temp && ./temp ; rm temp 2>/dev/null ; exit
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *next;
struct node *prev;
int priority;
};
struct node *head;
void add_item(int priority)
{
struct node *curr = head;
struct node *prev = NULL;
while((curr != NULL) && (curr->priority < priority)) {
prev = curr;
curr = curr->next;
}
struct node *new = malloc(sizeof(struct node));
new->priority = priority;
new->next = curr;
new->prev = prev;
if(prev != NULL) {
prev->next = new;
} else {
head = new;
}
}
void remove_item(int priority)
{
struct node *curr = head;
while((curr != NULL) && (curr->priority != priority)) {
curr = curr->next;
}
if(!curr)
return;
if(curr == head) {
head = curr->next;
} else {
curr->prev->next = curr->next;
if(curr->next)
curr->next->prev = curr->prev;
}
free(curr);
}
void delete_list()
{
struct node *curr;
while(head != NULL) {
curr = head;
head = head->next;
free(curr);
}
}
void print_items()
{
int member = 0;
for(struct node *iter = head; iter != NULL; iter = iter->next)
{
printf("Member: %d -> priority: %d\n", member, iter->priority);
member++;
}
}
int main(int argc, char** argv)
{
printf("This file is self-compiling\n");
add_item(1);
add_item(1);
add_item(2);
add_item(3);
add_item(1);
add_item(5);
add_item(4);
add_item(3);
remove_item(1);
remove_item(4);
remove_item(5);
add_item(5);
print_items();
delete_list();
}