Re: insert [sorted] a node in a linked list
On Sunday, 10 March 2013 09:48:20 UTC+2, alexo wrote:
Il 09/03/2013 15:52, ?????? Tiib ha scritto:
On Friday, 8 March 2013 17:20:30 UTC+2, alexo wrote:
I'd like to insert a node in a linked list in a sorted manner. from
smaller to bigger
Can you tell us the reason why you use linked list for sorted
container? I would likely review such usage as a design defect.
It's for testing my programming skills.
I read in the book "teach yourself C++ in 21 days" that the author did so
in one of his lessons [on appendix E, for the precision].
So I thought I could handle a similar thing with my code. That's it.
Sounds like "drop 50 pounds of weight in 21 days". Can be done but result
might be not that nice.
What I can't figure out is how to do as better as I did,
so I asked you an help. What's wrong with my code?.
Since it is sorted container ... move unsorted inserts like push()
and push_back() to private.
Learn to use debugger.
Lets look at your code:
while(temp != 0)
{
Why while is better than if? It does only one cycle
if( value > temp->getValue() )
{
Node * new_node = new Node(value);
insert(new_node, temp);
break;
It breaks cycle here ...
}
else
{
push(value);
break;
.... and here ...
}
temp = temp->next;
.... and above line is no way reachable.
}
So ... the error is somewhere here, you probably wanted to do something
else entirely.
Feels you over-engineered and so got confused in resulting mess
of classes without clear responsibilities. Your list has unneeded
first element (Head). It has no responsibilities. Make the class
Linked_List to take over the unexisting responsibilities of Head.
To have such Head you have split classes Node and List_Element.
Merge them back.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]