Insertion Linked List Help
Basically, I need to be able to insert values into a blank list and able to print them out once the user has finished all the inputs.
Heres what I done so far:
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
struct Node *link;
int value;
} Node;
int insert_list(Node **linkp, int new_value);
void print_list(Node *list);
int main(int argc, char **argv)
{
int *root;
root = malloc(sizeof(Node));
int value;
int i = 0;
/* Insert statements here */
while ((i = scanf("%d",&value)) != 0)
insert_list(root,value);
print_list(root);
free(root);
return 0;
}
void print_list(Node *list)
{
Node *current;
current = list;
while (current->value != NULL)
{
printf("%d ",current->value);
current = current->link;
}
}
int insert_list(Node **linkp, int new_value)
{
Node *current;
Node *previous;
Node *new;
/* Point to the first node */
previous = NULL;
current = *linkp;
/* Look down the list until the node has a value has a smaller value
than the new_value variable */
while (current != NULL && current->value < new_value)
{
previous = current;
current = current->link;
}
/* Allocate a new node and store the new value */
new = (Node *)malloc(sizeof(Node));
if (new == NULL)
{
printf("Not enough memory available!\n");
return 1;
}
new->value = new_value;
/* Insert the new node to the list */
new->link = current;
if (previous == NULL)
*linkp = new;
else
previous->link = new;
return 0;
}
I'm quite stumped on what the error is, I'm pretty sure my insert function is correct and my print function looks alright as well. Not sure if I'm using it properly.. any help would be awesome :)
Thanx in advance..