-
List of nodes
I have a struct as follows
Code:
struct node{
int x;
int y;
node *next_nodex;
}
node r_table[360];
These are delcared globally. I know this is bad but it does initilise everything if declared globally.
I have a function which decides which element in the array.
How would I get to the last element in one of the lists. Is it something like this.
Code:
node *tmp_ptr;
tmp_ptr = &(r_table[table_indx]);
// Goto to end of list
while (tmp_ptr->next_node != NULL)
tmp_ptr = tmp_ptr->next_node;
// Add new node
tmp_ptr->next_node = new(node);
// Step into new node
tmp_ptr = tmp_ptr->next_node;
tmp_ptr->x = x_anchor - col;
tmp_ptr->y = y_anchor - row;
tmp_ptr->next_node = NULL;
Thanks
-
Looks good - but here is an optimization:
Code:
typedef struct _node
{
int x;
int y;
_node *next_nodex;
_node() : next_nodex(NULL) {}
} node_t;
typedef struct _node_array_elem
{
node_t *first,*last;
_node_array_elem() : first(NULL),last(NULL) {}
} node_array_elem_t;
node_array_elem_t r_table[360];
...
node_array_elem_t *tmp_ptr;
tmp_ptr = r_table + table_indx;
node_t *new_node = new(node_t);
// Add new node
if (tmp_ptr->last != NULL)
{
tmp_ptr->last->next_nodex = new_node;
tmp_ptr->last = new_node;
}
else
{
tmp_ptr->last = new_node;
tmp_ptr->first = new_node;
}
new_node->x = x_anchor - col;
new_node->y = y_anchor - row;
If you are using "new", then you must be using C++, so you can also use constructors to perform initialization (which also means the typedef's are really necessary, but I like em). And then the optimization part: why traverse to the end of the list every time if you can just remember where the end is?
gg