Hello, I'm having a problem with inserting into a linked list... It seems when I'm trying to insert something into the head I get a runtime error. I assumed that I would be safe from the runtime error because the || statement is supposed to be short circuit evaluated. I'll bold the part I'm talking about.
Code:
#include <stdio.h>
struct node{
int data;
struct node* next;
};
void insert(struct node** head, int data);
void printlist(struct node* head);
int main(void)
{
int choice;
int data;
struct node* head; // our LL.
do
{
printf("Your choices: \n");
printf("(1) Add to list \n");
printf("(2) Print list \n");
printf("(0) quit \n");
scanf("%d",&choice);
if (choice == 1)
{
printf("What data would you like to insert?\n");
scanf("%d",&data);
insert(&head,data);
}
if (choice == 2)
{
printlist(head);
}
} while (choice != 0);
printf("Goodbye\n");
system("PAUSE");
}
//Inserts in order from smallest to largest
void insert(struct node** head, int data)
{
struct node* current;
struct node* temp;
//If inserting into the beginning of the list
if (*head == NULL || (*head)->data > data)
{
temp = malloc(sizeof(struct node));
temp->data = data;
temp->next = *head;
*head = temp;
return;
}
//Traverse list to find the spot we're in
current = *head;
while (current->next != NULL && current->next->data < data)
{
current = current->next;
}
//Insert in middle or the end
temp = malloc(sizeof(struct node));
temp->data = data;
temp->next = current->next;
current->next = temp;
return;
}
void printlist(struct node* head)
{
struct node* current;
current = head;
while (current->next != NULL)
{
printf("%d",current->data);
current = current->next;
}
}
I must be doing something wrong. Thanks for the help everyone.