c - 如何创建单链表数组
问题描述
我正在尝试创建一个链表数组,其中每个列表的节点都是字母表中的一个字符,因此该数组应该有 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。
解决方案
代替:
struct Node list[26]
和struct Node *list[26]
list[x] = *first
和list[x] = first
append(&list[x], name)
和append(list[x], name)
struct Node list[26]
是 的数组struct Node
,但您想要一个指向 的指针数组,数组的每个元素struct Node
都是指向列表头部的指针。
奖励:您的append
功能非常低效。为了将元素附加到列表中,您必须遍历整个列表才能找到最后一个元素。您应该维护指向列表最后一个元素的指针。
推荐阅读
- google-apps-script - 用户缓存和用户属性 GAS
- .htaccess - .htaccess 代码将动态链接重定向到新的动态链接
- google-cloud-dataflow - google cloud-dataflow java管道中的条件跳过
- webpack - 如何限制 webpack 4 中生成的捆绑包数量以供输入?
- asp.net-mvc - 在 web.config 文件中全局验证文本框控件的 html 标记输入
- angularjs - 加载资源失败,(服务不可用)错误 503
- ios - 使用 UIscrollview 的委托功能上下滚动隐藏和显示视图
- android - Android MediaPlayer 是否支持 HTTP 部分内容
- ms-access - 访问运行时错误 - '-2147352567
- c# - C# 按字母顺序排序字符串数组,注意首先放置以大写字母开头的字符串。第一的