-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
85 lines (70 loc) · 1.79 KB
/
list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "list.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>
static car_t *front = NULL;
/*
static void print_car(car_t *cp) {
printf("%s\n", cp->plate);
}
*/
/* put(): place a car at the beginning of the list
* returns 0 if successful; nonzero otherwise
*/
int32_t lput(car_t *cp) {
if (!cp) {
fprintf(stderr, "Error: Value of cp is null\n");
return 1;
}
cp->next = front;
front = cp;
return 0;
}
/* get(): remove and return the first car in the list;
* return NULL if the list is empty
*/
car_t *lget() {
if (!front) {
fprintf(stderr, "Error: List is empty, returns NULL\n");
return front;
}
car_t *first_element = front;
front = front->next;
return first_element;
}
/* apply a function to every car in the list */
void lapply(void (*fn)(car_t *cp)) {
if (!front) {
fprintf(stderr, "Error: Function cannot be applied to empty list\n");
}
car_t *current_car = front;
while (current_car) {
fn(current_car);
current_car = current_car->next;
}
}
/* remove(): find, remove, and return any car with
* the designated plate; return NULL if not present
*/
car_t *lremove(char *platep) {
if (!front) {
fprintf(stderr, "Error: List is empty, returns NULL\n");
return front;
}
if (strcmp(front->plate, platep) == 0) {
return lget();
}
else {
car_t *current_car = front->next;
car_t *previous_car = front;
while(current_car) {
if (strcmp(current_car->plate, platep) == 0) {
previous_car->next = current_car->next;
return current_car;
}
previous_car = current_car;
current_car = current_car->next;
}
}
return NULL;
}