This is what I have so far:
void sort(const E &t)
{
DNode<E> *tmp = new DNode<E>(t,NULL,NULL);
if(size==0)
{
cout << "List is empty" << endl;
}
else if(t<=head->element)
{
tmp->element=t;
head->prev = tmp;
tmp->next=head;
head = tmp;
}
else if(t>=tail->element)
{
tmp->element=t;
tail->next = tmp;
tmp->prev=tail;
tail = tmp;
}
curr=tmp;
insert(t);
size++;
}
insert() is just another function in my program:
void insert(const E &t)
{
DNode<E> *tmp = new DNode<E>(t,NULL,NULL);
if (size == 0)
{ curr=head=tail=tmp; }
else
{
tmp->next=curr;
tmp->prev=curr->prev;
if (curr->prev) curr->prev->next=tmp;
else { head=tmp; }
curr->prev=tmp;
curr=tmp;
}
size++;
}
It does compile, but it doesn’t give the correct results. I’m not sure what my errors are, and I would really need help.
Any help would be appreciated.
This is in my main program:
one.sort(10);
one.sort(20);
one.sort(30);
one.sort(40);
one.sort(50);
one.sort(60);
one.print();
one.moveToEnd();
one.prev();
one.prev();
one.remove();
one.remove();
one.print();
cout<<endl;
I should be getting this:
HEAD==> 10 -> 20 -> 30 -> 40 -> 50 -> 60 <==TAIL
HEAD==> 10 -> 20 -> 50 -> 60 <==TAIL
But I get this instead:
HEAD==> 10 -> 20 -> 20 -> 30 -> 30 -> 40 -> 40 -> 50 -> 50 -> 60 -> 60< ==TAIL
HEAD==> 10 -> 20 -> 20 -> 30 -> 30 -> 40 -> 40 -> 60 -> 60 <==TAIL
The cause of the behavior you’re seeing is that your missing an else
this:
is executed whether you have added something to the head or tail, or not. Since each entry you give will be added to the tail, it gets inserted twice each time. You should only call insert if you have not yet added the value to the head or tail.
If I understand correctly,
curr=tmp;andsize++;should be run regardless, so only the call to insert should be inside an else block, I think.EDIT:
Should look like this:
I’ve (kinda) maintained your whitespace usage, though I find it a bit unusual, by the way. I would normally place related ‘if’ ‘else if’ and ‘else’ statements on the same indention level, and indent further for nested blocks. I think that’s more standard, but neither here nor there.