c - 单链表中没有给我数据的第一个节点有什么问题
问题描述
这是完整的代码:我希望有人可以帮助我解决这个问题
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
struct word_count {
char* word;
int count;
struct word_count* next;
};
/* Introduce a type name for the struct */
typedef struct word_count WordCount;
/* Global data structure tracking the words encountered */
WordCount* word_counts = NULL;
/* The maximum length of each word in a file */
#define MAX_WORD_LEN 64
void init_words(WordCount** wclist) {
/* Initialize word count. */
wclist = NULL;
//wclist = (WordCount*)malloc(sizeof(WordCount));
}
现在我添加了这个功能来解决这个问题:
char* new_string(char* str) {
return strcpy((char*)malloc(strlen(str) + 1), str);
}
如果列表不为空,此函数将节点添加到列表末尾
void add_word(WordCount** wclist, char* word) {
WordCount* temp;
temp = (WordCount*)malloc(sizeof(WordCount));
if (temp == NULL) {
printf("error");
return;
}
else {
temp->word = word;
temp->count = 1;
temp->next = NULL;
}
if (*wclist == NULL)//the list is empty
*wclist = temp; //first node
else//this list is not empty
{
WordCount* p;
p = wclist;
while ((p->next) != NULL) {
p = p->next;
}
p->next = temp; //add new node to end of the list
}
}
打印列表的功能:
void printList(WordCount** wclist)
{
if(wclist==NULL)
{
printf("empty");
return;
}
WordCount* wc = NULL;
wc=wclist;
while (wc != NULL)
{
printf("[ %s | %d ]->", wc->word, wc->count);
wc = wc->next;
}
}
这是主要的:
int main()
{
init_words(&word_counts);
char* strings[] = { "abc","def","aaa","bbb","zzz","aaa" };
add_word(&word_counts, strings[0]);
add_word(&word_counts, strings[1]);
add_word(&word_counts, strings[2]);
add_word(&word_counts, strings[3]);
add_word(&word_counts, strings[4]);
add_word(&word_counts, strings[5]);
printList(&word_counts);
}
例如,当我将单词插入列表时,第一个节点不会出现
input:
> "abc" "def" "aaa" "bbb" "zzz" "aaa"
the output:
> [ X{δ | 1 ]->[ def | 1 ]->[ aaa | 1 ]
解决方案
推荐阅读
- r - gridExtra::tableGrob 中的 vp 参数如何工作?
- arrays - Fortran - 如何将 2dim 数组的行提取为新的 1dim 数组
- python - 为什么 % 有效和/不过滤偶数?
- pointers - 指向只有 dummy 为目标的变量的指针分配
- javascript - 窗口未定义服务器端渲染(react + express)
- sql - SQLite - 滚动平均/总和
- javascript - FindAll 不包含在 sequelize 中的元素
- django - Django 对 UI 元素进行分组
- reactjs - React - 通过 useContext 共享变量,以更新和重新渲染组件,但不起作用
- spring-boot - 使用 Spring Cloud Stream Kafka Binder + Kafka Streams Binder 的 Spring Boot 应用程序不起作用 - 生产者不发送消息