链接列表与字符串

时间:2015-10-14 04:10:49

标签: c linked-list

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

#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的新手:(

2 个答案:

答案 0 :(得分:2)

您的代码包含几个错误。首先,您要分配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;
  }

答案 1 :(得分:0)

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