Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define SIZE 32
- typedef struct _cargo {
- char code[SIZE];
- struct _cargo *next;
- }cargo;
- typedef struct _ship {
- char name[SIZE];
- cargo *cargoList;
- struct _ship *next;
- }ship;
- void showAll(ship **primeShip) {
- ship *primary = *primeShip;
- cargo *secondary = NULL;
- while (primary != NULL) {
- printf("%s\n", primary->name);
- secondary = primary->cargoList;
- while (secondary != NULL) {
- printf(" --- %s\n", secondary->code);
- secondary = secondary->next;
- }
- primary = primary->next;
- }
- }
- // add ship in primary list
- void addPrimary(ship **first, ship *toAdd) {
- ship **ptr = first;
- while ((*ptr)->next != NULL) {
- // iterate through list until last element is found
- ptr = &(*ptr)->next;
- }
- (*ptr)->next = toAdd;
- }
- // wrapper for addPrimary()
- void addPrimaryFromStdin(ship **first) {
- ship *toAdd = malloc(sizeof(ship));
- *toAdd = (ship){0};
- printf("Name for ship:\n");
- fgets(toAdd->name, SIZE, stdin);
- toAdd->name[strlen(toAdd->name) - 1] = 0; // get rid of newline char
- addPrimary(first, toAdd);
- }
- // add cargo in secondary list
- void addSecondary(cargo **first, cargo *toAdd) {
- cargo **ptr = first;
- while ((*ptr) != NULL) {
- // iterate through list until last element is found
- ptr = &(*ptr)->next;
- }
- (*ptr) = toAdd;
- }
- // wrapper for addSecondary()
- void addSecondaryFromStdin(cargo **first) {
- cargo *toAdd = malloc(sizeof(cargo));
- *toAdd = (cargo){0};
- printf("Name for cargo:\n");
- fgets(toAdd->code, SIZE, stdin);
- toAdd->code[strlen(toAdd->code) - 1] = 0; // to get rid of newline char
- addSecondary(first, toAdd);
- }
- // deletes all lists
- void init(ship **first) {
- cargo **cargoPtr = &(*first)->cargoList;
- ship **ptr = first;
- while ((*ptr) != NULL) {
- while ((*cargoPtr) != NULL) {
- free(*cargoPtr);
- cargoPtr = &(*cargoPtr)->next;
- }
- free(*ptr);
- ptr = &(*ptr)->next;
- }
- }
- int main() {
- ship *primeShip = malloc(sizeof(ship));
- *primeShip = (ship){0};
- addPrimaryFromStdin(&primeShip);
- addPrimaryFromStdin(&primeShip);
- addSecondaryFromStdin(&(primeShip->cargoList));
- addSecondaryFromStdin(&(primeShip->cargoList));
- showAll(&primeShip);
- init(&primeShip);
- showAll(&primeShip);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement