For our list of primes we need a list (naturally). The best way to understand data structures is to implement them in a low level language. Since I don't feel like inflicting ASM on everyone (although I do like assembler) we will use the next best thing. C
Out list needs a data element (the found prime) and a pointer to the next element.
In C that looks like this.
struct prime_elem_s {
uint64_t prime;
struct prime_elem_s *next;
};
We define a structure containing the current prime and a pointer to the next element. Then we define a type prime_elem_t to refer to that structure.
In this case we want to add elements to the end of the list so we will also need a tail pointer. We will create a list header which will keep a head and tail pointer as well as the number of elements in the list.
typedef struct {
uint64_t length;
prime_elem_t *head;
prime_elem_t *tail;
} prime_list_t;
Now we can write a function which appends a new prime to the list.
void push_prime(prime_list_t *prime_list, uint64_t prime)
{
prime_elem_t *elem = malloc(sizeof(prime_elem_t));
elem->prime = prime;
elem->next = NULL;
if( prime_list->tail )
{
prime_list->tail->next = elem;
prime_list->tail = elem;
}
else
{
prime_list->head = prime_list->tail = elem;
}
prime_list->length++;
}
Here we:
Out list needs a data element (the found prime) and a pointer to the next element.
In C that looks like this.
struct prime_elem_s {
uint64_t prime;
struct prime_elem_s *next;
};
typedef struct prime_elem_s prime_elem_t;
We define a structure containing the current prime and a pointer to the next element. Then we define a type prime_elem_t to refer to that structure.
In this case we want to add elements to the end of the list so we will also need a tail pointer. We will create a list header which will keep a head and tail pointer as well as the number of elements in the list.
typedef struct {
uint64_t length;
prime_elem_t *head;
prime_elem_t *tail;
} prime_list_t;
Now we can write a function which appends a new prime to the list.
void push_prime(prime_list_t *prime_list, uint64_t prime)
{
prime_elem_t *elem = malloc(sizeof(prime_elem_t));
elem->prime = prime;
elem->next = NULL;
if( prime_list->tail )
{
prime_list->tail->next = elem;
prime_list->tail = elem;
}
else
{
prime_list->head = prime_list->tail = elem;
}
prime_list->length++;
}
Here we:
- allocate a new element
- initialize its fields
- if this isn't the first element then append it to the list's tail then update the tail pointrewolf
- otherwise set both the head and tail to the new element
- increment the list's length
Comments
Post a Comment