/*#include headers here */
struct list_el {
int val;
struct list_el * next;
};
typedef struct list_el Item;
Item *list, *tail; //references to the linked list
int main() {
int i;
Item *curr;
int array[] = {1, 24,3,412,125,6,74,228,9, 10};
/*initialize the list*/
list = (struct Item*)malloc(sizeof(Item));
list->next=NULL; // this is important to
list->val = 0; // avoid wierd looking variables occupying our list
tail = list;
/*populate the list*/
for(i = 0; i
{
addToList(array[i]);
}
curr = list;
while(curr->next != NULL)
{
printf(“%d -> “, curr->val);
curr = curr->next;
}
printf(“%dn”, tail->val); //the tail isn’t really printed coz a tail triggers the loop to end
}
addToList(int value)
{
Item *curr;
if(tail == list && tail->val == NULL) //if the list is empty
{
tail->val = value; //create the head, since it’s the only element
tail->next = NULL; //it is also the tail
}
else
{
if(curr = (struct Item*)malloc(sizeof(Item)))
{
curr->val = value; //create a new node
curr->next = NULL; //new node becomes the tail — essentially, coz it doesn’t have anything after it
tail->next = curr; //the old tail links with the new node, so essentially it’s no longer a tail
tail = curr; //the new node is now formally a tail
}
else
{
printf(“nOut of memory errorn”);
system(‘pause’);
}
}
}