【发布时间】:2017-05-24 02:41:26
【问题描述】:
我正在这个简单的程序中工作,但我在传递指针时遇到了麻烦。
假设我有一个学生结构
typedef struct student{
char lastname[50];
int age;
int std_id;
struct student * next;
struct student * prev;
}stdn;
我还有另一个类结构
typedef struct class{
char class_id[3];
struct class * next;
struct class * prev;
struct student * stdn_list;
}clss;
所以基本上我有这个班级列表,每个班级都包含一个学生子列表。
所以,这是创建类列表的函数,它可以工作!
void create_class_list(clss ** root, clss * node){
clss * root_aux;
if(!(*root)){
(*root) = node;
}
else{
root_aux = (*root);
while(root_aux->next != NULL){
root_aux = root_aux->next;
}
node->prev = root_aux;
root_aux->next = node;
}
}
我的问题是当我需要使用类列表的每个节点中的子列表时。
这是负责创建子列表的函数,它起作用了
void assign_student(clss ** root, stdn * node, char * class_id){
clss * root_aux;
stdn * stdn_aux;
root_aux = (*root);
while(root_aux != NULL){
if(strcmp(root_aux->class_id,class_id) == 0)
break;
root_aux = root_aux->next;
}
if(root_aux != NULL){
if(root_aux->stdn_list == NULL){
root_aux->stdn_list = node;
}
else{
stdn_aux = root_aux->stdn_list;
while(stdn_aux->next != NULL){
stdn_aux = stdn_aux->next;
}
node->prev = stdn_aux;
stdn_aux->next = node;
}
}
}
基本上,此函数会查找特定班级并将学生添加到该班级。
我的问题是,当我想删除一个学生,或使用诸如冒泡排序之类的算法对列表进行排序时,这里有一个删除学生的函数示例。
void delete_student(clss ** root, int stdn_id){
clss * root_aux;
stdn * stdn_aux;
stdn * temp;
int deleted=0;
root_aux = (*root);
while(root_aux != NULL){
stdn_aux = root_aux->stdn_list;
//try with root first//
if(stdn_aux->std_id == stdn_id){
temp = stdn_aux;
stdn_aux = stdn_aux->next;
stdn_aux->prev = NULL;
free(temp);
deleted = 1;
}
//if the student isn't the root
if(deleted == 0){
stdn_aux = stdn_aux->next;
while(stdn_aux != NULL){
if(stdn_aux->std_id == stdn_id){
temp = stdn_aux;
//link the prev element with the next element
stdn_aux->prev->next = stdn_aux->next;
//link the next element with the prev element
stdn_aux->next->prev = stdn_aux->prev;
stdn_aux = stdn_aux->next;
free(temp);
deleted = 1;
break;
}
stdn_aux = stdn_aux->next;
}
}
if(deleted == 1){
break;
}
root_aux = root_aux->next;
}
}
该函数看起来就像不要从列表中删除元素,我不确定是否与我如何将指针传递给函数,或者我如何首先创建列表有关。
【问题讨论】:
-
`stdn_aux->next`可以为空
-
请发送minimal reproducible example。 MCVE 应包括各种样本输入(说明所有方面)和所需的输出。如果您正在寻求有关调试代码的帮助,请参阅ericlippert.com/2014/03/05/how-to-debug-small-programs
标签: c list pointers linked-list