带字符串的链表

Linked lists with strings

我正在尝试创建一个程序,首先解析多个字符串并将它们添加到链接列表中,然后打印出每个字符串的出现。

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Node Node;

struct Node
{
    char* word;
    int count;
    struct Node *next;
};

Node *head = NULL;
Node *curr = NULL;

Node* listAdd(char* word, bool toEnd) {
    Node* tmp = head;
    while (tmp) {
        if (strcmp(tmp, word) == 0) {
            tmp->count++;
            return tmp;
        }
        tmp = tmp->next;
    }
    printf("allocate memory for node");
    Node *ptr = malloc(sizeof(Node));

    printf("initialize count to 0");
    ptr->count = 0;

    printf("allocate memory to hold word");
    ptr->word = malloc(strlen(word) + 1);

    printf("copy the current word");
    strcpy(ptr->word, word);

    ptr->next = NULL;

    if (toEnd)
    {
        curr->next = ptr;
        curr = ptr;
    }
    else
    {
        ptr->next = head;
        head = ptr;
    }
    return ptr;
}

void printList()
{
    Node *ptr = head;
    while (ptr)
    {
        printf("\nThe word [%s] has had [%d] occurrences.\n",ptr->word, ptr->count);
        ptr = ptr->next;
    }
}

char* readWord()
{
    static char buffer[100];
    scanf("%s", buffer);
    printf("listAdd() call");
    listAdd(buffer);
    return buffer;
}

int main(void)
{
    int i = 0;
    printf("How many words would you like to type?\n");
    scanf("%d", &i);
    for (i; i != 0; i--)
    {
        readWord();
    }
    printList();
}

当前输出:

How many words would you like to input?
3
hi
bye
yes
How many words would you like to input?
Occurrences: 12086064

任何帮助将不胜感激 — 我仍然是 C# 的 C 新手:(

你需要用malloc和strcpy来存储单词,用strcmp来比较。您正在做的是保存对您正在读入单词的缓冲区数组的重复引用。

您的代码包含一些错误。首先,你分配你的 Node ptr 两次:

Node* listAdd(char* word, bool toEnd) {
  // .. 

  Node *ptr = malloc(sizeof(Node));
  return ptr;
}

删除最后一个,就在 return 语句之前。

您还需要分配内存来保存每个读取的单词。现在你每次调用 readWord() 时都会覆盖缓冲区。然后你会做这样的事情:

Node* listAdd(char* word, bool toEnd) {
  // allocate memory for node
  Node *ptr = malloc(sizeof(Node));
  // initialize count to 0
  ptr->count = 0;
  // allocate memory to hold word
  ptr->word = malloc(strlen(word) + 1);
  // copy the current word
  strcpy(ptr->word, word);

您的 printList() 函数需要如下所示:

void printList() {
  Node* ptr = head;
  while(ptr) {
    printf("Word: %s %d\n", ptr->word, ptr->count);
    ptr = ptr->next;
  }
}

由于您从不检查输入的单词是否已存在于您的列表中,因此每个单词将始终被报告为出现 1 次。这可以这样解决:

// check if the word alreay exists in the list and then increment its count by 1
// this code should go at the top (before allocating ptr) in listAdd()
Node* tmp = head;
while(tmp) {
   if(strcmp(tmp->word, word) == 0) {
     tmp->count++;
     return tmp;
   }
   tmp = tmp->next;
}

当然,您还应该在退出应用程序之前释放分配的内存:

void freeList() {
  Node* ptr = head;
  Node* tmp = 0;
  while(ptr) {
    tmp = ptr->next;
    free(ptr->word);
    free(ptr);
    ptr = tmp;
  }