首页 > 解决方案 > 如何创建单链表数组

问题描述

我正在尝试创建一个链表数组,其中每个列表的节点都是字母表中的一个字符,因此该数组应该有 26 个元素。我试图通过给每个元素的第一个节点字符串“。”来做到这一点。然后使用插入

这是我的链表定义

struct Node{
    char *name;
    struct Node *next;
};

void printList(struct Node *node)
{   printf("[");
    while (node !=NULL){
        printf("%s,", node->name);
        node = node->next;
    }
    printf("]\n");
}
struct Node *current = NULL;

void append(struct Node* head, char* new_data)
{
    /* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    new_node->name = new_data;
    new_node->next = NULL;

    if(head == NULL){
        head = new_node;
        return;
    }
    else{
        while(head->next != NULL){
            head = head->next;
        }
        head->next = new_node;
        return;
    }
}

这是 main 函数,在其中,我创建了一个字母表字符串,然后使用 for 循环更新数组中的每个链表。

int main(){
struct Node list[26];
    for(int x=0; x<26; x++){
        struct Node* first = (struct Node*) malloc(sizeof(struct Node));
        first->name = ".";
        first->next= NULL;
        list[x] = *first;

    }
    char *al = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


    for(int x = 0; x<26; x++){
        char name[2];
        name[0] = al[x];
        name[1] = '\0';
        printf("%s\n", name);
        append(&list[x], name);

    }


    return 0;
}

循环之后,LinkedList 的所有名称值都是 Z,而不是从 A 到 Z。

*edit i 打印数组内每个链表的第二个节点

for(int n =0; n<26; n++){
        printf("%s\n", list[n].next->name);
    }

这是结果

Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z
Z

它应该是从 A 到 Z 而不仅仅是 Z。

标签: cstringsingly-linked-list

解决方案


代替:

  • struct Node list[26]struct Node *list[26]
  • list[x] = *firstlist[x] = first
  • append(&list[x], name)append(list[x], name)

struct Node list[26]是 的数组struct Node,但您想要一个指向 的指针数组,数组的每个元素struct Node都是指向列表头部的指针。

奖励:您的append功能非常低效。为了将元素附加到列表中,您必须遍历整个列表才能找到最后一个元素。您应该维护指向列表最后一个元素的指针。


推荐阅读