链表数组,移动到下一个节点出错。

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*”)不是结构体或联合体。


在我的头文件中,我将节点定义为typedef struct node *nodeType; - CGTheLegend
@user2416553 对我来说,那里有很多指针,你可能根本不需要。 - Kraken
@user2416553,就“设计”而言,Kraken的建议非常好。我已经根据您的设计更新了我的答案。 - rahul maindargi
2个回答

1
如果您想要链表数组,为什么要使用指针?
struct List{
    adjListType list[10];
    int size;
};

当然你也可以使用指针,但是你需要展示如何使用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作为引用返回,否则会创建不必要的副本...

我正在查看您的代码,如果发现其他问题,我会更新此答案...同时,如果您能告诉我们您遇到了什么错误,那就太好了。

另外,在您展示的代码中,您将nextprevcurrent设置为NULL,但是您在哪里更改这些值呢...否则您将继续收到NULL POINTER EXCEPTION


是的,我正在使用calloc,我已经读取了一个输入来确定数组的大小。而且,我确实在使用Calloc。 - CGTheLegend
我正在使用指针,因为它们将非常有用于我即将创建的未来函数。 - CGTheLegend
我在adjListType前面添加了“struct”,结果报错:对不完整类型'struct adjListType'使用了无效的'sizeof'应用。 - CGTheLegend
当我插入/创建一个节点时,我也会初始化next、previous、first、current和last的值。 - CGTheLegend
如果 sizeof(struct List) 没有问题,那么 sizeof(struct adjListType) 有什么问题吗?请检查拼写错误。 - rahul maindargi
不,它给了我一个“对不完整类型'struct adjListType'使用'sizeof'的无效应用程序”错误。 - CGTheLegend

0
创建一个指向struct node的指针数组。这足以用于链表数组。
数组的每个元素,即指向struct node的指针将充当列表的头,并且可以通过随后添加/删除列表元素来维护列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接