-
Linked List Help
Hello! I've been having quite a struggle trying to conquer linked lists.
Here is a portion of code. Essentially, it creates a node and appends it to the end of a linked list. Or theoretically, that's what it should do.
Here is my linked list node definition.
Code:
typedef struct node
{
char last[1024];
char first[1024];
char position;
int value;
struct node *link;
}Node;
Essentially, in my main, I call my insertNode function whenever I want to add a new node. It works fine for two nodes, as well as the error case of if the node->last already exists within the list for these two nodes. However, when I try to enter a third node, the function will promp me to enter values for last, first,position and value. However, after this, the function simply doesn't proceed or exit. It just stops working. I can hit letters and spaces and hit enter on the keyboard and it will just print these on screen. I'm having trouble identifying why my function stops working after two nodes.
Thanks in advance!
Here's the insertNode function.
Code:
Node *insertNode (Node *head)
{
Node *node = (Node *)malloc(sizeof(Node));
Node *current = head;
char lastName[1024];
printf(" family name: ");
safegets(lastName,MAX_LENGTH+1);
printf(" first name: ");
safegets(node->first,MAX_LENGTH+1);
printf(" position: ");
scanf("%c",&(node->position));
getchar();
printf(" value: ");
scanf("%d",&(node->value));
getchar();
node->link=NULL;
if (head==NULL)
{
strcpy((node->last),lastName);
return node;
}
else if (head->link == NULL)
{
strcpy((node->last),lastName);
if (strcmp(lastName,head->last)==0)
{
familyNameDuplicate(lastName);
return head;
}
head->link=node;
return head;
}
while (current->link != NULL);
{
if (strcmp(lastName,current->last)==0)
{
familyNameDuplicate(lastName);
return head;
}
current=current->link;
}
strcpy((node->last),lastName);
current->link=node;
return head;
}
}
-
Can you post how you call your function?
-
while (current->link != NULL);
Try dropping that semicolon. It's an infinite loop since that semicolon means there's no loop body and thus current isn't being incremented (your actual loop body is treated as just a section of code in braces).
Also, in the future, please post your code with proper indenting and make sure we have enough code to compile your program and reproduce the error (provide your safegets function and a small main function with 3 insertNode calls, e.g.).
-
Essentially, I first declare the head
There is a do loop that prompts the user for input of either I, D, S, V, P or Q to quit. The section with the function is:
Code:
if (response == 'I')
{
head = insertNode(head);
}
-