我试图通常添加到链接列表,因为我有2个链接列表,我为这两个列表调用相同的函数。
void addToList(void* (*createNode)(void *data,char* name), int (compare)(void *a1, void *a2), void *(*getNext)(void), void(*setNext)(void *node, void* data), void *data,char* name, void **list) {
void *node = createNode(data,name);
void *head = *list;
if (head == NULL) { // if list is empty
*list = node;
}
else if (compare(head, node)) { // if first element is greater than node to add (meaning we need to add node to head of list)
setNext(node, list);
*list = node;
}
else {
// node will be inserted someplace other than head
void *current = head;
while (getNext(current) != NULL && compare(node, getNext(current))) {
// loop until we are at the end of the list OR until we have found an element greater than us
// basically, current will be the place to put the new node in
current = getNext(current);
}
setNext(node, getNext(current));
setNext(current, node);
}
这是结构,列表和节点
struct Stud {//my struct contains 2 lists
int id;
float gradeAverage;
float incomeAverage;
struct gradeList *gradelist;
struct incomeList *incomelist;
};
typedef struct Stud Students;
struct gradeNode {//the grade node with what is inside it
char courseName[20];
int grade;
struct gradeNode *next;
struct gradeNode *prev;
};
struct gradeList {//my first list with head and tail
struct gradeNode *head;
struct gradeNode *tail;
int size;
};
struct incomeNode {//my secound node
char *workplace;
float income;
struct incomeNode *next;
struct incomeNode *prev;
};
struct incomeList {//the secount list
struct incomeNode *head;
struct incomeNode *tail;
int size;
};
以下是我使用的功能
void* get_next_Income(void* head) {//used above in the generic call
return((struct incomeNode *)head)->next;
}
void* get_next_Grade(void* head) {//used above to get the income
return(((struct gradeNode *)head)->next);
}
int compareGradeNode(void *a1, void *a2) {//compares the node iam adding to the exicting node and adding accordingly
return ((struct gradeNode*)a1)->grade > ((struct gradeNode*)a2)->grade;
}
int compareIncomeNode(void *a1, void *a2) {
return ((struct incomeNode*)a1)->income>((struct incomeNode*)a2)-
>income;
}
void setNextGradeNode(void* node, void* data) {//seting the next graded
((struct gradeNode*)node)->next = data;
}
void setNextIncomeNode(void* node, void* data) {//setting the next income
((struct incomeNode*)node)->next = data;
}
Students students[30];
int numOfStuds = 0;
void* createGradeNode(void* data,char*name) {
struct gradeNode* nd=(struct GradeNode*)malloc(sizeof(struct gradeNode));
strcpy(nd->courseName, name);
assert(nd != NULL);
nd->grade = data;//setting the new node to the data the user entered!
nd->next = NULL;
return nd;//and return it
}
问题是我在下面的代码部分得到了一个空ptr 我正在使用visual studio而无法解决它 请帮忙。 很抱歉长代码,我是c的新手。
void *head = *list;
if (head == NULL) { // if list is empty
*list = node;