c - 单链单词列表

标签 c list linked-list words

我正在尝试编写一个函数words,它根据作为参数传递的文本生成单链接的单词列表(由空格分隔的字符序列)。结果列表中的单词应该与文本中的单词相同。

不幸的是,程序在运行时出错,您能否解释一下出了什么问题,我也希望得到一些提示。代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

struct node{
    char* word;
    struct node* next;
};

void printList(struct node* list){
    struct node* it = list;
    while(it != NULL){
        printf("%s ", it -> word);
        it = it -> next;
    }
    printf("\n");
}

void insertLast(struct node* tail, char* neww){
    tail -> next = (struct node*)malloc(sizeof(struct node));
    tail = tail -> next;
    tail -> word = neww;
    tail -> next = NULL;
}

struct node* words(char* s){
    char* slowo = strtok(s, " ");
    struct node* head;
    struct node* tail;
    if (sizeof(slowo) == 0)
        return NULL ;
    head = (struct node*)malloc(sizeof(struct node));

    head -> word = slowo;
    head -> next = NULL;
    tail = head;
    slowo = strtok(NULL, " ");
    while (slowo != NULL){
        insertLast(tail, slowo);
        tail = tail -> next;
        slowo = strtok(NULL, " ");
    }
    return head;
}

int main() {
    printList(words("Some sentance la al olaalal"));
    getch();
    return (EXIT_SUCCESS);
}

最佳答案

如果您不想 insertLast 在调用函数中设置 tail,则必须通过引用传递指针(即作为指向指针的指针。) :

void insertLast(struct node** tail, char* neww)

insertLast 中使用正确的解引用才能使其正常工作。

关于c - 单链单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9160965/

相关文章:

c - 双链表的堆栈模拟

c - 将用户输入存储到两个数组中

c - WTSEnumerateServers ERROR_INVALID_DOMAINNAME

C# 列出两个引用?

c - 删除节点后打印结构链表时出错

java - Append Method Linked List...它不断删除最后一个输入

c - Libwebsockets 发送数据

c++ - Ubuntu 11.10 上的 OpenCV

python - 如何获取字典中的其他值然后一个值等于

python - 在多词字符串列表中,提取第二个词