[edit]
Okay, so I should set root to point to a new node, and then just set the root->next value? What about root->value? Isn't it still unitialized? 'root' isn't supposed to contain a 'value', correct?
Don't point root to a new node. Point it to NULL. That way root->value can be a real value in your list, rather than being a sentenial. [/edit]
Think of it this way. Say you had an array, and you were using it as a stack.
Code:
int data[MAX], pos;
What you're doing is something like this:
Code:
void init_stack() {
data[0] = -1;
pos = 0;
}
You set data[0] to something, in this case -1, but in your case a new node. Then you set pos to reference to the last element in the stack, in this case, data[0].
Then you insert stuff into this data structure like this.
Code:
void insert_value(int value) {
pos ++; /* "allocate" new node */
data[pos] = value;
}
Now you've added a value to the array/list, and pos once again points to the last element.
But, as you can probably see, you've skipped over data[0]. Here's the same code laid out in linear fashion.
Code:
data[0] = -1;
pos = 0;
pos ++; /* "allocate" new node */
data[pos] = value;
You can see that data[0] is not set to a proper value. Sure, it's set to -1. But when you go to print the list or something, you'll get -1 and then your real values.
You could get around this by having your printing functions start printing at data[1]. But this is just an ugly hack. It would make much more sense to allow an empty data structure.
In this case, because pos has to point to the last element, an empty structure is represented with pos=-1.
Code:
void init_stack() {
pos = -1;
}
The insert_value() code would work in this case, although with your linked list you'd have to add a special case, for when the list is empty, to assign the new node to root.
The printing code just then has to make sure there's something in the list. In this case, something like
Code:
for(x = 0; x <= pos; x ++)
would handle things automatically. You can do this with linked lists, too, if you're careful.
Code:
void print_list() {
node *pos = root;
while(pos) {
print_node(pos);
}
}