In article <11**********************@k78g2000cwa.googlegroups .com>,

as*******@gmail.com wrote:

Hello all:

I would like to insert a number into a linked list in ascending order.

Is the following function correct?

void insert(Node **node, int v)

{

Node *tmp = (Node *)malloc(sizeof(Node));

while(*node && (*node)->value < v) node = &(*node)->next;

tmp->value = v;

tmp->next = *node;

*node = tmp;

}

What happened when you tested it? For example, what happens with the

following main? (You may need to #include <cassert)

int main()

{

Node* n = 0;

insert( &n, 2 );

assert( n->value == 2 );

assert( n->next == 0 );

insert( &n, 4 );

assert( n->value == 2 );

assert( n->next->value == 4 );

assert( n->next->next == 0 );

insert( &n, 7 );

assert( n->value == 2 );

assert( n->next->value == 4 );

assert( n->next->next->value == 7 );

assert( n->next->next->next == 0 );

insert( &n, 5 );

assert( n->value == 2 );

assert( n->next->value == 4 );

assert( n->next->next->value == 5 );

assert( n->next->next->next->value == 7 );

assert( n->next->next->next->next == 0 );

}

If this is correct, how to answer the following case:

Given a linked-list as follows:

NodeA(2) -NodeB(4) -NodeC(7) -NULL.

Insert 5.

Then the new linked-list will become as follows if I understand

correctly.

NodeA(2) -NodeB(4) -NodeC(7) -NULL

NodeD(5) -NodeC(7)

You answer it however you think it should be answered. Does the problem

require the insert function to maintain a sorted list? What should the

insert function do if the list passed in wasn't sorted in the first

place?

Ask your instructor to please show his students how to test their code

so they will know, before turning it in, if it is correct.

I've tutored several people going to several different colleges, and it

always amazes me that not one of the teachers seem to bother teaching

their students how to test code for conformance to the spec.