ArchiSys/TP/TP1/rendu/linked_list.c
2024-03-31 18:26:34 +02:00

125 lines
2.5 KiB
C

// linked list
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "linked_list.h"
linkedList* createLinkedList() {
linkedList *list = (linkedList*)malloc(sizeof(linkedList));
list->head = NULL;
return list;
}
//insert link at the first location
void insertFirst(linkedList *list, int key, void *data) {
//create a link
node *link = (node*) malloc(sizeof(node));
link->key = key;
link->data = data;
//point it to old first node
link->next = list->head;
//point first to new first node
list->head = link;
}
//delete first item
node* deleteFirst(linkedList *list) {
if (!list->head) {
return NULL;
}
//save reference to first link
node *tempLink = list->head;
//mark next to first link as first
list->head = list->head->next;
//return the deleted link
return tempLink;
}
//find a link with given key
node* find(linkedList *list, int key) {
//start from the first link
node* current = list->head;
//if list is empty
if(!current) {
return NULL;
}
//navigate through list
while(current->key != key) {
//if it is last node
if(!current->next) {
return NULL;
} else {
//go to next link
current = current->next;
}
}
//if data found, return the current Link
return current;
}
//delete a link with given key
node* deleteElement(linkedList *list, int key) {
//start from the first link
node* current = list->head;
node* previous = NULL;
//if list is empty
if(!list->head) {
return NULL;
}
//navigate through list
while(current->key != key) {
//if it is last node
if(!current->next) {
return NULL;
} else {
//store reference to current link
previous = current;
//move to next link
current = current->next;
}
}
//found a match, update the link
if(current == list->head) {
//change first to point to next link
list->head = list->head->next;
} else {
//bypass the current link
previous->next = current->next;
}
return current;
}
//is list empty
bool isEmpty(linkedList *list) {
return !list->head;
}
int length(linkedList *list) {
int length = 0;
node *current;
for(current = list->head; current != NULL; current = current->next) {
length++;
}
return length;
}