// Battle Royale Linked List Demo
// Part 1: Creating a linked list using a function
// that creates a single node.
// Looping through the list and printing out the names
// Marc Chee (cs1511@cse.unsw.edu.au) October 2020
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
struct player {
struct player *next;
char name[MAX_NAME_LENGTH];
};
struct player *create_player(char *newName, struct player *newNext);
void printPlayers(struct player *playerList);
int main(void) {
struct player *head = NULL;
head = create_player("Marc", head);
head = create_player("Chicken", head);
head = create_player("Aang", head);
head = create_player("Katara", head);
printPlayers(head);
return 0;
}
// create player allocates memory for a new player and
// populates it with newName and newNext.
// returns a pointer the the newly created player
struct player *create_player(char *newName, struct player *newNext) {
struct player *newPlayer = malloc(sizeof (struct player));
strcpy(newPlayer->name, newName);
newPlayer->next = newNext;
return newPlayer;
}
// takes the pointer to the head of a list of players
// prints their names, one per line
void printPlayers(struct player *playerList) {
struct player *curr = playerList;
while (curr != NULL) {
//fputs(curr->name, stdout);
//putchar('\n');
printf("%s\n", curr->name);
curr = curr->next;
}
}
Resource created Friday 30 October 2020, 05:30:30 PM.
file: battleRoyale.c