Hi
Julia wrote:
> Obviously using an insertion sort on a linked list is a waste of time,
> energy and space. However, some of the other solutions I have seen to
> this puzzel have consisted of transferring the data from the linked
> list to an array, sorting the array and transferring the data back to a
> linked list. I would like to do this without using that many extra
> memory locations.
Why don't you use in-place merge-sort or quick-sort?
In-place merge-sort should be easy to implement.
> Hmmm... should the while statement be
> (conductor->x < conductor->next->x) && (0 != conductor->next)
Actually it would be better to test for conductor->next != 0 _first_, before
trying to dereference conductor->next:
(0 != conductor->next) && (conductor->x < conductor->next->x)
Also, you would have to return after the loop in case 0 == conductor->next,
because then your list is completely sorted.
>> > node *temp, *temp2;
>> > temp = new node;
>> > temp2 = new node;
>> > temp = root;
>> > temp2 = root;
>> > while(conductor->next->x > temp->x)
>> > {
>> > temp2 = temp;
>> > temp = temp->next;
>> > }
Some more remarks:
1. You have a memory leak here. You allocate two nodes and immediately
discard all pointer pointing to them.
2. Looks like you're trying to find the two nodes temp2 and temp between
which conductor should be inserted. You should use the
invariant "temp2->next == temp", so you had better initialize temp with
root->next (more intelligible). At the same time, you might think about
renaming these variables ("temp" is rarely a good name).
> Should I add the same thing here?
In fact you needn't, as you know that eventually temp->x >=
conductor->next->x (hint: temp == conductor)
You should also consider using a wrapper class (mylist?) around your nodes
so that you cannot pass around internal nodes but only complete lists.
Secondly, I don't see the point in passing conductor as an argument instead
of declaring it as a local variable...
Markus
|