C语言 创建链表负责人时出现问题



我的代码旨在从散列链表中读取一系列字符串,将它们全部转换为小写,将它们放入数组以对它们使用快速排序,然后将它们放入称为字数的数据结构中,其中包括单词及其在文档中出现的次数。目前,当我运行代码时,它使用我正在使用的打印语句正确打印出来,但是当我打印出来时,头部总是设置为 null。

这是字数声明:

typedef struct wordCount
{
int count;
char *word;
struct wordCount* next;
} wordCount;

这是应该执行我上面描述的方法段。

else
{
char *toSort[curSize];
int linkedListTraverse = 0; //Array index for each linked list node
while(linkedList != NULL)
{
toSort[linkedListTraverse] = (char*) malloc(sizeof(linkedList->string));
strcpy(toSort[linkedListTraverse],linkedList->string); //Copy the data from the linked list into an array 
linkedList = linkedList->next;
linkedListTraverse++;
}
int i = 0;
while(i < curSize) //Convert all of the words to lowercase
{
char* str = toSort[i];
char *p;
for (p = str; *p != ''; p++)
*p = (char)tolower(*p);
i++;
}
i = 0;
qsort(toSort, curSize, sizeof(char*), stringCmpFunc); //Sort the current node
while(i < curSize)
{
printf("%sn", toSort[i]);
i++;
}
int curWordIndex = 0;
int checkWordIndex = 1;
wordCount *wordHead = NULL;
wordCount *curWord = wordHead;
while(curWordIndex < curSize)
{
curWord = (wordCount*) malloc(sizeof(wordCount));
curWord->word = toSort[curWordIndex]; //Set the word
curWord->count = 1; //Start the count out at 1
while(strcmp(toSort[curWordIndex], toSort[checkWordIndex]) == 0) //While the two words are equal
{
checkWordIndex++; //Advance the leading index check
curWord->count++;
if(checkWordIndex >= curSize) //If the leading index goes beyond the array bounds
break;
}
if(checkWordIndex < curSize)
{
curWordIndex = checkWordIndex;
checkWordIndex = curWordIndex + 1;
}
if(checkWordIndex >= curSize) //If the leading index goes beyond the array bounds
{
if(strcmp(curWord->word, toSort[curWordIndex]) != 0)
{
printf("%s %dn", curWord->word, curWord->count);
curWord = curWord->next;
curWord = (wordCount*) malloc(sizeof(wordCount));
curWord->word = toSort[curWordIndex]; //Set the word
curWord->count = 1; //Start the count out at 1
}
break;
}
//printf("CurWordIndex: %dn CheckWordIndex: %dn",curWordIndex, checkWordIndex);
printf("%s %dn", curWord->word, curWord->count);
curWord = curWord->next; //Advance to the next node in the linked list
}
printf("%s %dn", curWord->word, curWord->count);

这是仅打印空的代码段

curWord = wordHead;
while(curWord != NULL)
{
printf("%s %dn", curWord->word, curWord->count);
curWord = curWord->next;
}

Put

if (wordHead == NULL) { wordHead = curWord; }

curWord = (wordCount*) malloc(sizeof(wordCount));

更新

这是另一个问题:

curWord = curWord->next;
curWord = (wordCount*) malloc(sizeof(wordCount));

它应该是:

curWord->next = (wordCount*) malloc(sizeof(wordCount));
curWord = curWord->next;

: 请遵守规则,这将有助于我们为您提供帮助。

更新/2

替换此内容:

while(curWordIndex < curSize) {
curWord = (wordCount*) malloc(sizeof(wordCount));

有了这个:

while(curWordIndex < curSize) {
wordCount* tmp = (wordCount*) malloc(sizeof(wordCount));
if (curWord) { curWord->next = tmp; }
curWord =  tmp;

相关内容

  • 没有找到相关文章

最新更新