Hello again,
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void insert(struct personStruct **root, char firstName[], char lastName[]);
void display(struct personStruct **root);
struct personStruct{
char first[999];
char last[999];
struct personStruct *next;
};
int main(void){
struct personStruct *root = NULL;
char resp[999];
do{
char firstName[999], lastName[999];
printf("%s", "\nPlease enter a choice, 9 for quit, or any other character to insert: ");
fflush(stdout);
scanf("%s", resp);
if(resp[0] != 9){
printf("\n%s", "Please enter the first name: ");
fflush(stdout);
scanf("%s", firstName);
printf("\n%s", "Please enter the last name: ");
fflush(stdout);
scanf("%s", lastName);
insert(&root, firstName, lastName); //pass a reference to a pointer (two levels of abstraction - why?)
}
}while(resp[0] != '9');
return 0;
}
void insert(struct personStruct **root, char firstName[], char lastName[]){
struct personStruct *tail = malloc(sizeof(struct personStruct)); //new tail pointer
printf("\nFirstname = %s", firstName);
strcpy(tail->first, firstName); //get my values into the tail pointer
strcpy(tail->last, lastName);
tail->next = NULL;
if(*root == NULL){ //if the root pointer is null
printf("\nRoot = null before");
*root = tail; //make the root pointer the pointer referenced by tail
printf("\nAfter, root = %s, %s", (*root)->first, (*root)->last); //this works - root has the values of tail
}
else{
struct personStruct *temp = *root; //temp pointer - assign it the value of the root pointer
while(temp->next != NULL){ //while not end of list
temp = temp->next; //iterate through
}
temp->next = tail; //at end of list, link the new pointer node on the end
free(temp); //free memory
}
free(tail); //free memory
display(root); //pass the reference to a pointer
}
void display(struct personStruct **root){
struct personStruct *temp = *root; //delare a temp pointer, and give it the value of the root pointer
int i = 1;
while(temp != NULL){ //while not end of list
printf("\n%d: %s %s", i, temp->first, temp->last); //print out current node value
fflush(stdout);
temp = temp->next;
i++;
}
free(temp); //free memory
}