通过链表迭代循环

Iterative loop through linked list

这个简单的程序创建了一个链接列表,其中包含首字母缩略词及其完整短语。有两个函数:

第一个创建一个节点,如果列表为空则将节点放在第一位,否则放在列表的末尾

void createNode(struct node **list, char *siglaElem, char *parolaElem) {
    struct node *new_node;
    new_node = malloc(sizeof(struct node));
    strcpy(new_node->sigla,siglaElem);
    strcpy(new_node->parola,parolaElem);
    new_node->next = NULL;

    if (*list == NULL) {
        *list = new_node;
    } else {
        while ((*list) != NULL) {
            (*list) = (*list)->next;
        }
        (*list)->next = new_node;
    }
}

第二个函数扫描整个列表。

int scanList(struct node **list, char *siglaElem, char *parolaElem) {
    struct node *scroll = *list;
    for (; scroll != NULL; scroll = scroll->next) {
        if (strcmp(scroll->sigla, siglaElem) == 0) {
            if (strcmp(scroll->parola, parolaElem) == 0)
                return 1;
            else 
                return 2;
        }
    }
    createNode(list, siglaElem, parolaElem);
    return 0;
}

main() 函数

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

struct node {
    char *sigla;
    char *parola;
    struct node *next;
};

int scanList(struct node **list, char *sigla, char *parola);
void createNode(struct node **list, char *siglaElem, char *parolaElem);

int main() {
    struct node *first = NULL;
    createNode(&first, "SI", "Sistema Informatico");
    createNode(&first, "OS", "Operating System");
    printf("%d %d\n", scanList(&first, "SI", "Sistema Informatico"), scanList(&first, "OS", "Operating System"));
    return 0;
}

我不明白为什么会出现分段错误:11

我认为我在循环方面做错了什么。 任何解决方案?

createNode 中的 else 子句中存在错误,您推进列表直到 (*list) 指向 NULL,然后您取消引用 (*list) -> 运算符,但正如我们所说,它已经指向 NULL 。可能会有更多错误,这只是让您继续前进的快速观察。如果您正在 linux 工作,我最近发现了一个名为 Nemiver 的用户友好调试器,试一试。

你的createNode函数有两个错误,第一个是你没有为sigla和parola分配内存,第二个错误是你改变了你的列表的主指针。

解决方案:

 void createNode(struct node **list, char *siglaElem, char *parolaElem) {

    struct node *new_node;
    struct node *tmp;

    new_node = malloc(sizeof(struct node));
    new_node->sigla = malloc(sizeof(char) * (strlen(siglaElem)+1));
    new_node->parola = malloc(sizeof(char) * (strlen(parolaElem)+1));

    strcpy(new_node->sigla, siglaElem);
    strcpy(new_node->parola, parolaElem);
    new_node->next = NULL;

    if (*list == NULL) {
       *list = new_node;
    } else {
       tmp = *list;
       while (tmp->next != NULL)
          tmp = tmp->next;
       tmp->next = new_node;
    }
}

我没有检查 malloc 的 return 但检查是为了确保你的变量被正确分配,你也可以使用 gdb 或 valgrind 来调试你的代码:) !