Velocity Reviews > beginners problem

# beginners problem

SM Ryan
Guest
Posts: n/a

 02-11-2008
# int main()
# {
# Node *nod = NULL;
# insert(&nod, 4); /* \$ */
# printf("%d\n", nod->data);
# printf("%10p\n", (void *) nod); /* \$ */
# printf("%10p\n", (void *) nod->next); /* \$ */
# return 0;
# }

# void insert(Node ** head /* \$ */ , int n)
# {
# Node *tmp;
# if (*head == NULL) { /* \$ */
# *head = alloc_node(n); /* \$ */
# }
#
# else {
# tmp = alloc_node(n);
# (*head)->next = tmp; /* \$ */
# }
# }

I prefer an applicative style. An equivalent to the above would be
...
nod = insert(nod,4);
...
Node *insert(Node * head, int n)
{
Node *tmp;
if (head == NULL) { /* \$ */
head = alloc_node(n); /* \$ */
}
else {
tmp = alloc_node(n);
head->next = tmp; /* \$ */
}
}

There may be a marginal difference that an applicative style is
easier for the compiler to optimise, but overall it is question
of which is easier for you to program in.

For example if you were to implement a stack, one might do pushes
push(&stack,a);
push(&stack,b);
...
or
stack = push(stack,a);
stack = push(stack,b);
...
or
stack = push(push(push(stack,a),b),...);

--
SM Ryan http://www.rawbw.com/~wyrmwif/
I ASSURE YOU WE'RE OPEN!