|
Department of Engineering |
|
|
Next: Using pointers instead of
Up: Examples
Previous: Calling other programs
Contents
Linked Lists
The following program creates a singly linked list. Pointers are
maintained to the head and tail of the list.
#include <stdio.h>
typedef struct _list_item {
int val;
struct _list_item *next;
} list_item;
/* prototypes */
list_item *add_list_item(list_item *entry, int value);
void print_list_items(void);
list_item *head=NULL;
list_item *tail=NULL;
main(int argc, char *argv[])
{
tail=add_list_item(tail,5);
tail=add_list_item(tail,7);
tail=add_list_item(tail,2);
print_list_items();
}
list_item *add_list_item(list_item *entry, int value)
{
list_item *new_list_item;
new_list_item=(list_item*)malloc(sizeof(list_item));
if (entry==NULL){
head=new_list_item;
printf("First list_item in list\n");
}
else {
entry->next = new_list_item;
printf("Adding %d to list. Last value was %d \n",value,entry->val);
}
new_list_item->val = value;
new_list_item->next = NULL;
return new_list_item;
}
void print_list_items(void)
{
list_item *ptr_to_list_item;
for (ptr_to_list_item= head;ptr_to_list_item!= NULL;
ptr_to_list_item=ptr_to_list_item->next) {
printf("Value is %d \n", ptr_to_list_item->val);
}
}
Tim Love
2010-04-27