Singly-linked-list.svg
One way to visualize a linked list is as though it were a train. The programmer always stores the first node of the list in a pointer he won’t lose access to. This would be the engine of the train. The pointer itself is the connector between cars of the train. Every time the train adds a car, it uses the connectors to add a new car. This is like a programmer using malloc to create a pointer to a new struct.
heres below the c program for the implementation of single linked list
#include <stdio.h > #include <conio.h > struct node { int x; struct node *next; }; int main() { /* This won't change, or we would lose the list in memory */ struct node *root; /* This will point to each node as it traverses the list */ struct node *conductor; root = malloc( sizeof(struct node) ); root->next = 0; root->x = 12; conductor = root; if ( conductor != 0 ) { while ( conductor->next != 0) { conductor = conductor->next; } } /* Creates a node at the end of the list */ conductor->next = malloc( sizeof(struct node) ); conductor = conductor->next; if ( conductor == 0 ) { printf( "Out of memory" ); return 0; } /* initialize the new memory */ conductor->next = 0; conductor->x = 42; return 0; }
That is the basic code for traversing a list. The if statement ensures that the memory was properly allocated before traversing the list. If the condition in the if statement evaluates to true, then it is okay to try and access the node pointed to by conductor.
The while loop will continue as long as there is another pointer in the next. The conductor simply moves along. It changes what it points to by getting the address of conductor->next.
Finally, the code at the end can be used to add a new node to the end. Once the while loop as finished, the conductor will point to the last node in the array. (Remember the conductor of the train will move on until there is nothing to move on to? It works the same way in the while loop.) Therefore, conductor->next is set to null, so it is okay to allocate a new area of memory for it to point to (if it weren’t NULL, then storing something else in the pointer would cause us to lose the memory that it pointed to).
When we allocate the memory, we do a quick check to ensure that we’re not out of memory, and then the conductor traverses one more element (like a train conductor moving on to the newly added car) and makes sure that it has its pointer to next set to 0 so that the list has an end. The 0 functions like a period; it means there is no more beyond. Finally, the new node has its x value set. (It can be set through user input. I simply wrote in the ‘=42’ as an example.)