简体   繁体   中英

I'm stuck on how to make a sorting algorithm in a doubly linked list using a person's first name and last name in C++

So I made a doubly linked list which stores a person's first name, last name, address and age and I am currently stuck on making a sorting algorithm for the list. So far I've managed to create 3 functions, one that adds a node to the list, one that deletes a node from the list and one which prints the list. Here's what I have so far, the struct:

    struct Node {
    string First_Name;
    string Last_Name;
    string Address;
    int age;
    Node* next;
    Node* prev;
} *first = 0, * last = 0;

The addToList function:

void addToList()
{
    string temp = "Yes";
    string First_Name;
    string Last_Name;
    string Address;
    int age;
    Node* current = first;

    while (temp == "Yes") {

        cout << "Enter the persons first name: ";
        cin >> First_Name;
        cout << "Enter the persons last name: ";
        cin >> Last_Name;
        cout << "Enter the persons age: ";
        cin >> age;
        cout << "Enter the persons address: ";
        cin >> Address;
        cout << "Would you like to add another person? Yes or No";
        cin >> temp;

        current = new Node;
        current->First_Name = First_Name;
        current->Last_Name = Last_Name;
        current->age = age;
        current->Address = Address;
        if (last) last->next = current;
        else first = current;
        current->prev = last;
        current->next = 0;
        last = current;
    }
    return;
}

And the print list:

void printList()
{
    if (!first)
    {
        cout << "Nothing is present in the list." << endl;
        return;
    }
    Node* current = first;
    while (current)
    {
        cout << current->First_Name << " " << current->Last_Name << " " << current->age << " " << current->Address << endl;
        current = current->next;
    }
}

My question is, how would I be able to sort the list alphabetically, I've never done sorting before... Thank you!!

To use custom sorting for a doubly-linked list, overload operator< :

struct Person
{
  std::string first;
  std::string last;
  std::string address;
  unsigned int age;
  bool operator<(const Person& p) const
  {
      bool is_less_than = false;
      if (last == p.last)
      {
          is_less_than = first < p.first;
      }
      else
      {
          is_less_than = last < p.last;
      }
      return is_less_than;
  }
};

Now you can use std::list and it will automatically sort by last name, then first. And std::list is a doubly-linked list.

To compare Person s:

  Person a;
  Person b;
  //...
  if (a < b)
  {
     std::cout << "Person A < Person B\n";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM