4

基本上我想要一个链表数组,每个链表都有自己的标题。这是我的代码:

struct node{
    int location;
    struct node *next;
    struct node *previous;
};

typedef struct ListHeader{
    nodeType *first;
    nodeType *current;
    nodeType *last;
} ListHeader;

struct adjList{
    ListHeader *header;
    int size;
};

struct List{
    adjListType *list;
    int size;
};

ListType newList(int numVerts){
    ListType new = malloc(sizeof(struct List));
    new->list = calloc(numVerts, sizeof(adjListType));
    new->size = numVerts;
    int i;
    for(i = 0; i <= numVerts; i++){
        new->list[i] = newAdjList();
    }
    return new;
}

adjListType newAdjList(void){
    adjListType new = malloc(sizeof(struct adjList));
    new->header = malloc(sizeof(ListHeader));
    new->header->first = NULL;
    new->header->current = NULL;
    new->header->last = NULL;
    new->size = 0; 
    return new;
}

nodeType newNode(int location){
    nodeType new = malloc(sizeof(struct node));
    new->location = location;
    return new;
}

当我尝试使用此代码(ListType l,int location)移动到链表中的下一个节点时,它给了我一个错误

l->list[location]->header->current = l->list[location]->header->current->next; 

这是我得到的错误:

成员引用基类型“nodeType”(又名“struct node*”)不是结构或联合

4

2 回答 2

1

如果你想要链表数组,为什么要使用指针?

struct List{
    adjListType list[10];
    int size;
};

当然,您也可以使用 Pointer,但是您需要向我们展示如何使用calloc


根据有问题的更新代码..以下是错误修复行...

ListType newList(int numVerts){
    ListType new = malloc(sizeof(struct List));
    new->list = calloc(numVerts, sizeof(struct adjListType));//Here you missed struct
    new->size = numVerts;
    int i;
    for(i = 0; i < numVerts; i++){ // Here <= instead of < for 10 length array is 0 to 9
        new->list[i] = newAdjList();
    }
    return new;
}

此外,您可能希望返回 &new 作为参考,否则您最终会创建不必要的副本...

我要去你的代码,如果我发现其他任何东西,我会更新这个答案。同时,如果你能告诉我们你得到了什么错误,那就太好了?

同样在您显示的代码中,您正在设置nextandprevcurrenttoNULL但您正在更改这些值的位置......否则您将继续获得NULL POINTER EXCEPTION

于 2013-05-24T07:42:08.770 回答
0

创建一个指向 的指针数组struct node。对于链表数组来说,这应该足够了。

数组的每个元素,即指向的指针struct node将充当列表的标题,并且可以通过随后从列表中添加/删除元素来维护列表。

于 2013-05-24T07:59:58.847 回答