I have a question about linked lists. I have this code below, which Im trying
to familirize myself with by carefully breaking down each statement...
But im having trouble with one line (see comments below).
Code:
struct list {
int data;
list *next;
};
int main() {
list *first, *last, *current // declare pointers to first, last, current elements in the linked list
int value; // this will store the value read from the user
first = (list*)malloc(sizeof(list)); // assign memory to the first element
first ->next=NULL; // make the first element point to NULL (since there are no more...
// ...elements at the moment)
last = first; // for the same reason, make last equal to first
printf("Enter a new value (-1 to exit): "); // prompt the user for a value
scanf("%d", &value); // ...and store it in value
while(value != -1) { // loop until -1 is entered
current = (list*)malloc(sizeof(list)); // allocate memory to the current element
current->data = value; // assign value entered to the current element
current->next = NULL; // make current element point to NULL
last = current; // make current element the last one in the list
last->next = current; // this part I don't quite understand. Why do we need the...
// ...last point to the current? Would it just point to itself? What's...
// ...the difference between the previous statement (last = current)
// ...and this one?
printf("Enter a new value (-1 to exit): "); // prompt for a new value
scanf("%d", &value); // store it
} // end of loop
/*
ignore these lines for the moment... I havent reached them yet... ^_^
current = first; // Get the first element
while(current->next != NULL) { // loop until end of list
current = current->next; // go to next element
printf("%d ", current->data); // display data
}
*/
}