Skip to content

Instantly share code, notes, and snippets.

@nhatminhbui
Last active July 30, 2021 07:49
Show Gist options
  • Save nhatminhbui/07c5173df46e08fb1d6ee939dfee94e0 to your computer and use it in GitHub Desktop.
Save nhatminhbui/07c5173df46e08fb1d6ee939dfee94e0 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct course {
char code[10];
int credit;
char name[50];
struct course *next;
};
typedef struct course course;
course* MakeNode(void) {
struct course* a;
a = (struct course *)malloc(sizeof(struct course));
if(a == NULL) {
puts("Some kind of malloc() error");
exit(1);
}
return a;
}
void AddCourse(course** head_ref, char code[10], int credit, char name[50]) {
course* c = MakeNode();
strncpy(c->code, code, 10);
strncpy(c->name, name, 50);
c->credit = credit;
c->next = *head_ref;
*head_ref = c;
}
void PrintAll(course* head) {
course* c;
for (c = head; c != NULL; c = c->next)
printf("%s \t %d \t %s\n", c->code, c->credit, c->name);
}
bool DeleteCourse(course** head_ref, char code[10]) {
course *iter = *head_ref;
course *prev = NULL;
while (iter->code != code) {
prev = iter;
iter = iter->next;
if (iter == NULL) return false; //out of list but not found
}
if (iter == *head_ref) {
*head_ref = iter->next;
free(iter);
} else {
prev->next = iter->next;
free(iter); // NUCLEAR BOMB!!!
}
return true;
}
void SortByCredit(course* head) {
// ASCENDING
for (course *i = head; i != NULL; i = i->next) {
// i = 1 to n
for (course *c = head; c->next != NULL; c = c->next) {
// c = 1 to n-1
if (c->credit > c->next->credit) {
course temp = *c;
*c = *c->next;
*c->next = temp;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment