Итак, я пытался реализовать метод вставки в классе DCSList, чтобы я мог вставить элемент в список и отсортировать его сразу после вставки. Я попытался написать следующий код:
void DCSList::addNode(const Contact& c){
DNodePtr ptr = new DNode(c);
if (isEmpty()){
//Case if list is empty
myFirst = ptr;
iterator = ptr;
ptr->next = ptr;
}
else{
//Create a pointer to traverse the list
DNodePtr temp = myFirst;
if (ptr->data < temp->data){
/*Case if contact to be added comes before the one that is in
pointe to by myFirst*/
//Make the next of the node to be added point to myFirst
ptr->next = temp;
/*Make the previous of the node in the list
point to the node pointed by ptr*/
temp->previous = ptr;
if (temp->next == myFirst){
//Case if there is only one node in the list
/*Make the next of the node in list point to the
node to be added*/
temp->next = ptr;
/*Make the myFirst & iterator pointers
point to the new first node*/
myFirst = ptr;
iterator = ptr;
ptr = NULL;
delete ptr;
}
else{
//Case if we have more than one node in the list
//We need to go to the last element
while (temp->next != myFirst)
temp = temp->next;
//We reached the last element
/*Make the next of the last element point to the node we need
to add*/
temp->next = ptr;
//Make myFirst point to the new node
myFirst = ptr;
ptr = NULL;
delete ptr;
}
}
else{
if(temp->next != myFirst){
while(temp->data < ptr->data){
temp = temp->next;
}
/*When we find a node that has a contact that comes after the
one we want to add then we add it before this node*/
ptr->previous = temp->previous;
temp->previous->next = ptr;
temp->previous = ptr;
ptr->next = temp;
}
else{
//We need to add at the end of the list
//Point the next of the last node to the node we need to add
temp->next = ptr;
//Point the previous of the new node to the last node in list
ptr->previous = temp;
//Make the next of the new node point to myFirst
ptr->next = myFirst;
}
}
}
}
Это основной метод:
#include "Contact.h"
#include "DCSList.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
Contact c("Gabriel" , "71/273331" ,"","09/223462");
Contact c4("Amir" , "76/123456" , "" , "09/234567");
Contact c2("Hamid", "71/1223456", "" , "06/431958");
Contact c3("Imad", "70/123456", "", "09/123457");
DCSList list;
list.addNode(c4);
list.addNode(c);
list.addNode(c3);
list.addNode(c2);
list.displayNode();
list.operator ++();
list.displayNode();
list.operator ++();
list.displayNode();
list.operator ++();
list.displayNode();
return 0;
}
После стольких тестов при написании этого метода я заметил, что у меня возникает ошибка, когда когда для Например, после вставки контактов, начинающихся с G, H и I, список был отсортирован. Но когда я пытаюсь добавить контакт, имя которого начинается с A. Этот контакт вставляется в конец списка, что неверно. Если вы поможете мне исправить этот метод, я буду очень благодарен.
Спасибо за внимание.