Okay, I'm just trying to insert values into a linked list (structs), and I must be doing the assignments wrong, but I can't see what it might be. Is it not simply tempPtr = tempPtr->next ? Can someone point me in the right direction here?
As usual, thanks in advance!
Code:
#include<stdio.h>
#include<stdlib.h>
struct personStruct{
char *fn, *ln;
struct personStruct *next;
}*root = NULL;
void display(struct personStruct* ps);
int main(void){
void insert(struct personStruct *ps, char *fn, char *ln);
char response[999], firstName[999], lastName[999];
char *resp = response, *first = firstName, *last = lastName;
while(1){
printf("%s", "\nPress (9) to quit; otherwise, any character to insert: ");
fflush(stdout);
scanf("%s", resp);
if(resp[0] == '9'){
return 0;
}
else{
printf("\nPlease enter the first name: ");
fflush(stdout);
scanf("%s", first);
printf("\nPlease enter the last name: ");
fflush(stdout);
scanf("%s", last);
insert(first, last);
}
}
}
void insert(char *first, char *last){
struct personStruct *tail = malloc(sizeof(struct personStruct));
tail->fn = first;
tail->ln = last;
tail->next = NULL;
if(root == NULL){
printf("%s", "\nroot = NULL");
fflush(stdout);
root = tail; //assign new value to root if empty list
}
else{
struct personStruct *temp = root; //else start a temp pointer at root to traverse the list
printf("\n%s %s %s %s", "In insert(), root->fn = ", root->fn, ", and root->ln = ", root->ln);
fflush(stdout);
while(temp->next != NULL){ //until end of list, display each struct's values
printf("\n%s %s %s %s", "In insert(), temp->next->fn = ", temp->next->fn, ", and temp->next->ln = ", temp->next->ln);
fflush(stdout);
temp = temp->next; //jump to next struct
}
fflush(stdout);
temp->next = tail; //end of list reached, put inserted node at end
}
display(root);
}
void display(struct personStruct *root){
struct personStruct *temp = root;
if(root == NULL){
printf("%s", "Uh-oh, root = NULL");
fflush(stdout);
}
else
while(temp != NULL){
printf("%s %s %s", "In display: ", temp->fn, temp->ln);
fflush(stdout);
temp = temp->next;
}
}