Linked List Example
#include <stdio.h>
typedef struct node
{
int info;
struct node *link;
} NODE;
void insert_front(NODE **ptr, NODE *new_one);
void print_list(NODE *ptr);
int main(void)
{
NODE *front = NULL;
NODE *new_one;
/**
gets the memory for new_node - a function to do this is needed
get_memory(&new_one);
new_one will be set to NULL if there is no memory and should be
checked for this. This code does NO error checking and should.
also, instead of "filling" the node within the main(), you need a
subprogram to fill one node. This is just part of the basic work
you need to do with every structure you create. The other is to
write a subprogram to write one node.
**/
new_one = (NODE *)malloc(sizeof(NODE));
(*new_one).info = 1;
(*new_one).link = NULL;
/**
front = new_one; if the list is empty, this actually puts the new node
at the front of the list.
**/
insert_front(&front, new_one);
print_list(front);
return (0);
}
/** This function currently only deals with the empty list
NOTE: the **prt is the address of the pointer to the front of the
list and the value stored in the pointer can be changed - it is
in out. new_one is simply a copy of a pointer. What it points
to can be changed (ie the fields in it) but where it points
can not be changed.
**/
void insert_front(NODE **ptr, NODE *new_one)
{
if (*ptr == NULL)
*ptr = new_one;
else
{
/* set pointer field in new_one to the value stored in ptr
set *ptr to new_one
*/
}
}
/** alternate solution to above. For your insert into an ordered list
you will use some of the ideas in this example
**/
/*
void insert_front(NODE **ptr, NODE *new_one)
{
NODE *current;
current = *ptr;
if (current == NULL)
current = new_one;
else
{
/* set pointer field in new_one to the value stored in current
set current to new_one
*/
}
*ptr = current;
}
/** start is a copy of a pointer. Where it points cannot be changed so
it is in only
**/
void print_list(NODE *start)
{
if (start == NULL)
{
printf("\nList is empty.\n");
}
else
{
printf("\n");
while(start != NULL)
{
/* instead of using the printf() here, call the write_one_node(start)
subprogram you should have created */
printf("%d ", (*start).info);
start = (*start).link;
}
}
}