最近一直在练习数据结构,但遇到一个新问题,当我尝试打印列表时,它提示“core dumped”,我很困惑!
我声明:
struct DOUBLE_LINK_LIST {
char *string;
struct DOUBLE_LINK_LIST *pre;
struct DOUBLE_LINK_LIST *next;
}double_link_list;
链接列表.h:
/* double linked list */
struct DOUBLE_LINK_LIST *init_double_link_list() {
struct DOUBLE_LINK_LIST *new_link = malloc(sizeof(struct DOUBLE_LINK_LIST));
if (new_link==NULL) {
fprintf(stderr, "Insufficient memory!!!");
return NULL;
}
new_link->string = NULL;
return new_link;
}
==============================这是我得到长度的方法:
int D_get_length(struct DOUBLE_LINK_LIST *link) {
int count;
count = 0;
while (link->next!=NULL) {
count += 1;
link = link->next;
}
return count;
}
int D_create(struct DOUBLE_LINK_LIST *link, char *in) {
if (D_get_length(link)>=STRING_SIZE) {
fprintf(stderr, "Double link list is full!!!");
return ERROR;
}
else {
struct DOUBLE_LINK_LIST *new_node;
new_node = init_double_link_list();
if (new_node==NULL) {
return ERROR;
}
/*new_node->next = link->next;
new_node->pre = link;
link->next = new_node;
if(new_node->next!=NULL) {
new_node->next->pre = new_node;
}
new_node->string = in;*/
new_node->next = link->next;
link->next = new_node;
new_node->string = in;
}
return OK;
}
它确实返回正确的长度,但它不在 create 函数中:
char *D_get_element(struct DOUBLE_LINK_LIST *link, int pos) {
int i;
if (D_is_empty(link)==YES) {
return NULL;
}
printf("_%d_", D_get_length(link));
if (pos <= 0 || pos-1 > D_get_length(link)) {
fprintf(stderr, "Invalid position!!!");
exit(1);
}
else {
for (i = 0; i < pos; ++i) {
link = link->next;
}
}
return link->string;
}