@@ -1,16 +1,16 @@
|
||||
#include "basics.h"
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
struct list *list_append(struct list *l, int e)
|
||||
{
|
||||
if (!l) return NULL;
|
||||
struct list *tmp = l;
|
||||
struct list *tmp = l;
|
||||
|
||||
struct list *new_node = calloc(1, sizeof(struct list));
|
||||
if (!new_node) return NULL;
|
||||
|
||||
new_node->data = e;
|
||||
if(!tmp) return new_node;
|
||||
if(!l) return new_node;
|
||||
|
||||
while (tmp->next) tmp = tmp->next;
|
||||
tmp->next = new_node;
|
||||
@@ -84,17 +84,99 @@ void list_destroy(struct list *l){
|
||||
free(l);
|
||||
}
|
||||
|
||||
struct list *list_find(struct list *l, int e){
|
||||
|
||||
if(!l) return NULL;
|
||||
|
||||
struct list *tmp = l;
|
||||
|
||||
while (tmp->data != e) tmp = tmp->next;
|
||||
|
||||
return tmp;
|
||||
|
||||
}
|
||||
|
||||
struct list *list_delete_at(struct list **l, size_t index){
|
||||
|
||||
struct list *old = *l;
|
||||
|
||||
if ( index == 0){
|
||||
*l = old->next;
|
||||
return old;
|
||||
}
|
||||
|
||||
struct list *tmp = *l;
|
||||
|
||||
size_t ind = 0;
|
||||
while(tmp->next != NULL && ind < index - 1){
|
||||
|
||||
tmp = tmp->next;
|
||||
ind ++;
|
||||
}
|
||||
|
||||
if (ind < index) {
|
||||
old = tmp->next;
|
||||
tmp->next = old->next;
|
||||
return old;
|
||||
}
|
||||
return NULL;
|
||||
|
||||
}
|
||||
int list_remove(struct list **l, int e){
|
||||
|
||||
struct list *old = *l;
|
||||
struct list *tmp = *l;
|
||||
|
||||
while (tmp->next != NULL && tmp->data != e){
|
||||
|
||||
tmp = tmp->next;
|
||||
}
|
||||
|
||||
if(tmp->data == e) {
|
||||
|
||||
old = tmp->next;
|
||||
tmp->next = old->next;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void list_print(struct list *l){
|
||||
|
||||
if(!l) {
|
||||
printf("\n");
|
||||
return ;
|
||||
}
|
||||
|
||||
struct list *tmp = l;
|
||||
|
||||
while (tmp != NULL){
|
||||
|
||||
printf("%i",tmp->data);
|
||||
|
||||
if (tmp->next != NULL) printf(" -> ");
|
||||
|
||||
tmp = tmp->next;
|
||||
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
struct list *l = NULL;
|
||||
|
||||
l = list_append(l, 42); // l = [42] -> NULL
|
||||
list_print(l);
|
||||
l = list_append(l, 7); // l = [7] -> [42] -> NULL
|
||||
list_count(NULL); // 0
|
||||
list_count(l); // 3
|
||||
list_print(l);
|
||||
|
||||
// Here, you should call "list_destroy(l);" when it will be implemented to
|
||||
// prevent any memory leak
|
||||
// l = [1] -> [2] -> [3]
|
||||
list_insert(&l, 1, 99); // l = [1] -> [99] -> [2] -> [3], and list_insert returns 0
|
||||
list_insert(&l, 9, 99); // list unchanged, returns 1
|
||||
|
||||
|
||||
list_destroy(l);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user