// Demo of insertion before the last element
// of a linked list, when we have a struct
// pointing at the start and end of the list
// Marc Chee (marc.chee@unsw.edu.au) 29/7/2019
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_NAME_LENGTH 33
struct location {
char name[MAX_NAME_LENGTH];
struct location *next;
};
struct realm {
struct location *lair;
struct location *castle;
};
// Insert a location into a realm just before the castle
void insert_location(struct realm *my_realm, char loc_name[MAX_NAME_LENGTH]);
void print_locations(struct realm *my_realm);
int main(void) {
// setup simple realm with a lair and castle
struct realm *azeroth = malloc(sizeof(struct realm));
azeroth->lair = malloc(sizeof(struct location));
azeroth->castle = malloc(sizeof(struct location));
strcpy(azeroth->lair->name, "The Dark Portal");
azeroth->lair->next = azeroth->castle;
strcpy(azeroth->castle->name, "Stormwind");
azeroth->castle->next = NULL;
printf("Testing creation of Realm\n");
print_locations(azeroth);
printf("--------\n");
printf("Expected output:\n");
printf("The Dark Portal\nStormwind\n");
printf("--------\n");
// try inserting some locations
insert_location(azeroth, "Swamp of Sorrows");
printf("Testing insertion before Castle\n");
print_locations(azeroth);
printf("--------\n");
printf("Expected output:\n");
printf("The Dark Portal\nSwamp of Sorrows\nStormwind\n");
printf("--------\n");
// try inserting many locations
insert_location(azeroth, "Wetlands");
insert_location(azeroth, "Redridge Mountains");
insert_location(azeroth, "Goldshire");
printf("Testing insertion of several locations\n");
print_locations(azeroth);
printf("--------\n");
printf("Expected output:\n");
printf("The Dark Portal\nSwamp of Sorrows\nWetlands\n");
printf("Redridge Mountains\nGoldshire\nStormwind\n");
printf("--------\n");
}
// Insert a location into a realm just before the castle
void insert_location(struct realm *my_realm, char loc_name[MAX_NAME_LENGTH]) {
// find the location just before the castle
struct location *search = my_realm->lair;
while (search->next != my_realm->castle) {
search = search->next;
}
// Insert new_node into list just before castle
struct location *new_node = malloc(sizeof(struct location));
new_node->next = my_realm->castle;
search->next = new_node;
strcpy(new_node->name, loc_name);
}
void print_locations(struct realm *my_realm) {
struct location *loc = my_realm->lair;
while (loc != NULL) {
fputs(loc->name, stdout);
putchar('\n');
loc = loc->next;
}
}
Resource created Monday 29 July 2019, 05:53:36 PM.
file: insert_location.c