我想在dl_list
上實現插入排序,其中包含char*
值,但運行程序(沒有警告,我使用gcc)後出現分段錯誤。C雙鏈表插入排序內存故障
這是我的結構:
struct node;
typedef struct node {
char *name;
char *surname;
char *birth_date;
char *email;
char *phone;
char *address;
struct node *next;
struct node *prev;
} node;
//doubly linked_list
typedef struct dl_list {
node *head;
node *tail;
} dl_list;
我按姓氏排序呢,後來的名字。我的名單上
int compare(node *alpha, node *beta) {
int a_surn_len = strlen(alpha->surname);
int b_surn_len = strlen(beta->surname);
for (int i = 0; i < ((a_surn_len > b_surn_len) ? b_surn_len : a_surn_len); i += 1) {
if (alpha->surname[i] > beta->surname[i]) return 1;
if (alpha->surname[i] < beta->surname[i]) return -1;
//if (alpha->surname[i] == beta->surname[i]) continue;
}
if (a_surn_len != b_surn_len) return a_surn_len > b_surn_len ? 1 : -1;
int a_n_len = strlen(alpha->name);
int b_n_len = strlen(beta->name);
for (int j = 0; j < ((a_n_len > b_n_len) ? b_n_len : a_n_len); j += 1) {
if (alpha->name[j] > beta->name[j]) return 1;
if (alpha->name[j] < beta->name[j]) return -1;
//if (alpha->surname[i] == beta->surname[i]) continue;
}
if (a_n_len != b_n_len) return a_n_len > b_n_len ? 1 : -1;
return 0;
}
這裏插入算法:當值同它返回0,如果alpha應該是公測前返回-1,否則1
dl_list *list_sort(dl_list *list) {
// zero or one element in list
if (list->head == NULL || list->tail == NULL)
return list;
// new_head is the first element of resulting sorted list
node *new_head = NULL;
while (list->head != NULL) {
node *current = list->head;
list->head = list->head->next;
// insert the first element into an empty sorted list
if (new_head == NULL) {
current->next = new_head;
new_head = current;
new_head->prev = NULL;
// or as the head of the sorted list
} else
if (compare(current, new_head) == -1) {
current->next = new_head;
new_head->prev = current;
new_head = current;
new_head->prev = NULL;
} else {
// insert current element into proper position in non-empty sorted list
node *ptr = new_head;
while (ptr != NULL) {
// middle of the list
if (compare(current, ptr->next) == -1) {
current->next = ptr->next;
ptr->next->prev = current;
ptr->next = current;
current->prev = ptr;
break; //done
// last element of the sorted list
} else
if (ptr->next == NULL) {
current->next = ptr->next;
ptr->next = current;
current->prev = ptr;
break;//done
}
ptr = ptr->next;
}
}
}
list->head = new_head;
node *ptr2;
for (ptr2 = list->head; ptr2->next != NULL; ptr2 = ptr2->next);
list->tail = ptr2;
return list;
}
我試圖檢查這個代碼在紙上,它似乎工作正常,在一些4-5元素清單。
有主?不知道這些例程是如何被調用的。 – Jiminion