我一直在努力解决这个问题,我似乎无法在C中创建有效的LinkedList
数据结构,
这是我的所有结构:
typedef struct {
int size;
int *cellsI;
int *cellsJ;
} DataInList;
typedef struct listElement{
DataInList dataVar;
struct listElement *next;
} LinkedListElement;
typedef struct {
LinkedListElement*first;
LinkedListElement*last;
} LinkedListRoot;
我有一个向链表添加数据元素的函数:
public void addDataToList(LinkedListRoot root, DataInList data) {
LinkedListElement newElem;
newElem.dataVar = data;
newElem.next = NULL;
if(root->first == NULL) {
root->first = &newElem;
root->last = &newElem;
} else {
root->last->next = &newElem;
root->last = &newElem;
}
}
有人可以帮我吗?
答案 0 :(得分:0)
正如评论者所说,你已经在函数中定义了 newElem,并且在堆栈中也是如此,因此你无法对其进行全球化或返回永久条目。这些更多的东西。我还没有测试过,但它应该给你一个想法:
typedef listData struct {
int size;
int *cellsI;
int *cellsJ;
} listData_t
typedef struct listElement {
listData_t dataVar;
struct listElement *next;
} listElement_t;
typedef struct listRoot {
listElement_t *first;
listElement_t *last;
} listRoot_t;
listElement_t *
addDataToList(listRoot_t *root, listData_t *data) {
listElement_t *newElem = malloc(sizeof(struct listElement));
if (newElem == NULL) {
fprintf(stderr, "Error allocating memory\n");
exit(-1)
}
newElem->dataVar = data;
newElem->next = NULL;
if (root->first == NULL) {
root->first = newElem;
root->last = newElem;
} else {
root->last->next = newElem;
root->last = newElem;
}
return newElem;
}