A linked list

/*#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

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
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
printf(“nOut of memory errorn”);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s