我正在尝试在我的add函数中按字母顺序排列两个单独的列表:一个按名字对节点进行排序,另一个按姓氏排序。我还有一些逻辑可以检查名称是否已在列表中,如果它是错误,则打印并且列表返回不变。就像标题所说,我在这里遇到了一个分段错误,不知道为什么。这可能是一个非常基本的问题,但我是C
新手,尤其是链表新手。
以下是节点的定义方式:
typedef struct node {
char *first;
char *last;
long number;
struct node *nextFirst;
struct node *nextLast;
} Node;
typedef struct mlist {
Node *headFirstName;
Node *headLastName;
} MultiLinkedList;
这是我的添加函数:
MultiLinkedList *add(MultiLinkedList *list, char *first, char *last, long num) {
// allocate a new node
Node *newNode = malloc ( sizeof(Node) );
newNode->first = malloc ( strlen(first) + 1 );
strcpy(newNode->first, first);
newNode->last = malloc ( strlen(last) + 1 );
strcpy(newNode->last, last);
newNode->number = num;
//make placeholder nodes
Node *a = list->headFirstName;
Node *b = list->headLastName;
// add this new node at the head of the "byFirst" list
if (strcmp(newNode->first, a->first) < 0) {
newNode->nextFirst = list->headFirstName;
list->headFirstName = newNode;
}
for (Node *i = list->headFirstName; i; i = i->nextFirst) {
// add after less alphabetical nodes
if (strcmp(newNode->first, i->first) > 0) {
newNode->nextFirst = i->nextFirst;
i->nextFirst = newNode;
}
// return error for duplicate name
if (strcmp(newNode->first, i->first) == 0 && strcmp(newNode->last, i->last) == 0) {
printf("That person is already in the list! Please try with a different name.n");
}
}
// add this new node at the head of the "byLast" list
if (strcmp(newNode->last, b->last) < 0) {
newNode->nextLast = list->headLastName;
list->headLastName = newNode;
}
for (Node *j = list->headLastName; j; j = j->nextLast) {
// add after less alphabetical nodes
if (strcmp(newNode->last, j->last) > 0) {
newNode->nextLast = j->nextLast;
j->nextLast = newNode;
}
}
// return the multi-list object with updated or original head pointers
return list;
}
我弄清楚了我的问题是什么。我必须在每个 if 语句的末尾添加 return list;
,否则该函数会尝试执行每个 true 语句;这会导致赛格故障。事后看来,我很惊讶我没有早点弄清楚这一点。