且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对具有多个元素的链表进行排序

更新时间:2023-11-10 09:36:58

要创建链接列表时,应使用包含两种日期类型的struct Cell:第一种是数据本身(在您的情况下为Contact))另一个是指向列表中下一个单元格的指针(下一个).使用这种类型的实现,您可以使代码更具可读性,模块化和可重用性.

When you want to create a linked list, you should use a struct Cell that contains two types of date: the first is your data itself (Contact in your case) the other is a pointer to the next cell in the list (next). Using this type of implementation you make your code more readable, modular and reusable.

typedef struct Contact
{
   char name[MAX];
   char number[MAX];
   char address[MAX];
   char email[MAX];
   struct Contact *next;
}
Contact;

typedef struct ContactCell {
   Contact info;
   struct ContactCell* next;
}
ContactCell;
typedef ContactCell* ContactList;

使用上面的功能实现

void addContactToList(ContactList start, Contact p)
{
   ContactCell* aux = malloc(sizeof(ContactCell));
   aux->info = p;

   aux->next = start;
   start = aux;
}

void printList(ContactList start)
{
   ContactList cursor = start;
   while (cursor != NULL)
   {
    printf("%s\n", cursor->info.name);
    cursor = cursor->next;
   }
}

对于排序,我会在单元格之间交换 info (使用上面的实现),因为这种方法使交换更容易理解,尤其是对于诸如Contact之类的数据类型(不重要)使用第三个变量进行交换).以下版本使用选择排序算法(效率不高,但更容易).

For the sorting I would have swapped the info between the cell (using the implementation above), because this method makes the swapped easier to understand especially for a type of data like Contact (not weighty to be swapped using a third variable). The following version uses selection sort algorithm (not super efficient, but easier).

void sorting(ContactList start)
{

  for (ContactList i= start; i!=NULL; i = i->next)
  {
     ContactList current_min = i;

     for (ContactList j=i->next ;j!=NULL; j = j->next)
        if (strcasecmp(current_min->info.name,j->info.name) > 0)
           current_min = j;

     //swap using a Contact aux variable
     Contact tmp = i->info;
     i->info = current_min->info;
     current_min->info = tmp;
  }

}