Сортировка двусвязного списка по алфавиту - PullRequest
0 голосов
/ 23 октября 2018

У меня есть задание, в котором я должен прочитать имена и веса из текстового файла и создать двусвязный список из информации.Один указатель DLL должен отслеживать отсортированные веса, а другой должен отслеживать отсортированные имена.Я реализовал функцию, которая считывает имена из текстового файла, и создал двусвязный список в отсортированном порядке, основанном на весах.Тем не менее, я не пытаюсь исправить указатели / ссылки, которые отслеживают алфавитный список, и я сталкиваюсь с большим количеством проблем.

    struct Node{
std::string name;
int weight;
Node* NextName;
Node* NextWeight;

Node(std::string newName, int newWeight){
    this -> name = newName;
    this -> weight = newWeight;
    this -> NextName = nullptr;
    this -> NextWeight = nullptr;
}
};

class DoublyLinkedList{
private:
Node* head;

public:
void sortByName(){
    setUpLinks();

    std::cout << "\n Sorted by name: " << std::endl;
    Node* tempHead = head;
    Node* current = head;
    Node* temp = head -> NextWeight;
    Node* prev = head;

    while(temp != nullptr){
        if(temp -> name < tempHead -> name){
            temp -> NextName = tempHead;
            tempHead = temp;
            temp = temp -> NextWeight;
        }

        else{
            while(current -> name < temp -> name){
                prev = current;
                current = current -> NextWeight;
            }
            if(current -> name > temp -> name){
                prev ->NextName = temp;
                temp -> NextName = current;
        }
    }
    temp = temp -> NextWeight;
    current = tempHead;
    }
}

void printByName(){
    Node* tempHead = head;
    while(tempHead != nullptr){
        std::cout << tempHead -> name << ", " << tempHead -> weight << "\n";
        tempHead = tempHead -> NextName;
    }
}

void printByWeight(){
    Node* temp = head;
    while(temp != nullptr){
        std::cout << temp -> weight << ", " << temp -> name << "\n";
        temp = temp -> NextWeight;
    }
}

void insert(std::string name, int weight){
    Node* temp = head;
    Node* prev = head;

    //Deals with the case of no nodes in the DLL yet
    if(head == nullptr){
        head = new Node(name, weight);
        temp = prev = head;
    }

    //Deals with case that new node is less than only node
    else if(weight < head -> weight){
        Node* newNode = new Node(name, weight);
        newNode -> NextWeight = head -> NextWeight;
        head = newNode;
        if(head -> name > head -> NextWeight -> name){
            head -> NextName = head -> NextWeight;
        }
    }

    //Find iteration
    while (temp -> weight <= weight){
        prev = temp;

        if(temp -> NextWeight == nullptr){
            Node* newNode = new Node(name, weight);
            temp -> NextWeight = newNode;
            return;
        }

        else temp = temp -> NextWeight;
    }

    Node* newNode = new Node(name, weight);
    newNode -> NextWeight = temp;
    prev -> NextWeight = newNode;


}

void setUpLinks(){
    Node* temp = head;
    Node* prev = head;
    while(temp != nullptr){
        prev = temp;
        temp = temp -> NextWeight;
        prev -> NextName = temp;
    }
}

};
int main(){
std::string name = "";
std::string firstName = "";
int weight = 0;
int iteration = 0;

DoublyLinkedList list;

ifstream inFile;
inFile.open("Names.txt");
if (!inFile) {
    std::cout << "Couldn't open file";
    exit(1);   // call system to stop
}
while (inFile >> name) {

    inFile >> weight;
    std::cout << "\nIteration " << iteration << ": \n";
    list.insert(name, weight);
    list.printByWeight();
    iteration ++;
}

list.sortByName();
list.printByName();
//list.printByName();
return 0;
}

Однако, похоже, я не получаю правильный отсортированный список в алфавитном порядке.Не уверен, в чем проблема.Мне кажется, этот код должен работать для сортировки по алфавиту.Любая помощь с благодарностью, это мой пример вывода ...

Iteration 14: 
99, Annabelle
124, Claire
145, Kevin
150, Jim
150, Brian
156, Bob
164, Steven
174, Michael
175, Chris
182, Jason
199, Abe
200, Richard
212, Tom

Sorted by name: 
Annabelle, 99
Chris, 175
Claire, 124
Jason, 182
Kevin, 145
Jim, 150
...