Skip to content

Instantly share code, notes, and snippets.

@1995parham
Last active January 2, 2020 15:25
Show Gist options
  • Save 1995parham/12684919529a6f2181208888d5a52cc5 to your computer and use it in GitHub Desktop.
Save 1995parham/12684919529a6f2181208888d5a52cc5 to your computer and use it in GitHub Desktop.
Students declarations and implementation of [W2](https://github.com/aut-ce/C-Workshops).
struct students *students_new(void) {
struct students *stds = malloc(sizeof(struct students));
stds->length = 0;
stds->head = NULL;
return stds;
}
void students_push_back(struct students *students, struct student *student) {
struct students_el *el = malloc(sizeof(struct students_el));
el->next = NULL;
el->student = student;
students->length++;
if (students->head == NULL) {
students->head = el;
} else {
struct students_el *p = students->head;
while (p->next != NULL) {
p = p->next;
}
p->next = el;
}
}
void students_remove(struct students *students, int index) {
struct students_el *el = students->head;
if (index == 0) {
students->head = el->next;
free(el->student);
free(el);
} else {
int i = 0;
while (el && i + 1 < index) {
el = el->next;
i++;
}
if (i + 1 == index) {
struct students_el *p = el->next->next;
free(el->next->student);
free(el->next);
el->next = p;
}
}
}
int students_search_id(struct students *students, const char *id) {
int index = -1;
int i = 0;
struct students_el *p = students->head;
while (p) {
if (strcmp(p->student->id, id) == 0) {
index = i;
break;
}
i++;
p = p->next;
}
return index;
}
struct student {
char name[256];
char id[8];
};
struct students {
int length;
struct students_el *head;
};
struct students_el {
struct student *student;
struct students_el *next;
};
struct students *students_new(void);
void students_push_back(struct students *students, struct student *student);
void students_remove(struct students *students, int index);
int students_search_id(struct students *students, const char *id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment