My project is a bubble sort system for doubly linked list. I am trying to sort elements of doubly linked list (which are objects) by Date. I used pointer-based sort because I do not want to change the data of pointers. The problem is my code can (I think efficiently) sort the linked list. But in the end, when I try to print objects of linked list, my head is not in place where it should be. Could you help me?
struct DoubleNode *DoubleDynamic::swap( DoubleNode *pointer1, DoubleNode *pointer2) {
DoubleNode* temp=pointer2->next;
pointer2->next=pointer1;
pointer2->prev=pointer1->prev;
pointer1->next=temp;
pointer1->prev=pointer2;
return pointer2;
}
void DoubleDynamic::sort(int size)
{
DoubleNode* temp;
DoubleNode* current;
bool sorting;
if (head==NULL)
{
return;
}else
{
for (int i = 0; i <= size; i)
{
sorting= false;
temp=head;
for (int j = 0; j < size-1-i; j)
{
DoubleNode *employee1=temp;
DoubleNode *employee2=employee1->next;
if (employee2!=NULL)
{
if (employee1->data->getAppointment().operator>(employee2->data->getAppointment()))
{
temp = swap(employee1,employee2);
sorting= true;
}
temp= temp->next;
}
}
if (!sorting)
{
break;
}
}
}
current=head;
while (current->prev!=NULL)
{
current=current->prev;
}
head=current;
}
void DoubleDynamic::display()
{
struct DoubleNode *trav;
trav=head;
if (trav==NULL)
{
cout<<"Liste boş yaa"<<endl;
}
while (trav != NULL)
{
cout<<*(trav->data)<<endl;
trav=trav->next;
}
cout<<endl;
}
CodePudding user response:
The problem is that when you swap the head pointer, you don't update head
to refer to the new head node.
One way to address this is after you do the swap, you should check to see if the head pointer should be updated.
temp = swap(employee1,employee2);
if (employee1 == head)
head = temp;
Alternatively, in swap
, if the new prev
pointer assigned in pointer2->prev=pointer1->prev;
is NULL then update the head (because the head node does not have a previous node).
if ((pointer2->prev=pointer1->prev) == nullptr)
head = pointer2;