【发布时间】:2016-11-13 18:06:52
【问题描述】:
我正在尝试按字母顺序对这个链接列表中的名称进行排序,但我不确定哪种方法是正确的。我创建了一个方法来比较列表中的名称并每次更新我的当前指针。我不断收到错误。有人可以建议一种更好的方法来对名称进行排序吗?我是 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;
}
【问题讨论】:
-
检查列表的开头。如果该元素的字典顺序大于您要插入的单词,请检查下一个元素。重复。如果您找到一个在字典上比您的单词少的单词,则在此处插入该单词。
-
链表很自然地适合归并排序。见stackoverflow.com/questions/35614098/…