我试图对这个链表中的名字按字母顺序进行排序,但我不确定应该采取什么样的方法。我创建了一个比较链表中名字并每次更新当前指针的方法。但我一直在出错。有人能建议一种更好的方法来遍历这些名字吗?我是C语言的新手,我很难找到一个更好的实现方法。任何帮助都将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HOW_MANY 7
char *names[HOW_MANY] = { "Ben", "Chris", "RDJ", "Mark", "Scarlet", "Samuel", "Tom" };
int ages[HOW_MANY] = { 22, 24, 50, 26, 18, 32, 24 };
/* declare your struct for a person here */
struct person {
char *name;
int age;
struct person *next;
};
static struct person *compare_people(struct person *headptr, struct person *headptr) {
int didSwap = 1, limit = HOW_MANY - 1;
struct person *temp;
struct person *previous = headptr;
struct person *new = headptr -> next;
while (didSwap) {
didSwap = 0;
for (int i = 0; i < limit; i++) {
if (strcmp(previous->name, new->name) > 0) {
temp = previous;
previous = new;
new = temp;
didSwap = 1;
}
}
limit--;
}
return temp;
}
static struct person *insert_sorted(struct person *headptr, char *name, int age) {
struct person *ptr;
// Allocate heap space for a record
ptr = malloc(sizeof(struct person));
if (ptr == NULL)
abort();
// Assign to structure fields
ptr->name = name;
ptr->age = age;
ptr->next = NULL;
if (headptr == NULL) {
ptr->next = headptr;
headptr = ptr;
} else {
struct person *currptr = headptr;
while (currptr != NULL) {
currptr = compare_people(headptr, headptr);
}
headptr = currptr;
}
return headptr;
}
int main(int argc, char **argv) {
// initialise the pointer to be empty
struct person *headptr = NULL;
// To insert all the info in the array
for (int i = 0; i < HOW_MANY ; i++) {
headptr = insert_sorted(headptr, names[i], ages[i]);
}
struct person *current = headptr;
while (current != NULL) {
printf("The person's name is %s and the age is %d.\n", current->name, current->age);
current = current->next;
}
return 0;
}