首页 文章

C中的字符串链表

提问于
浏览
-1

我正在尝试在C中创建字符串的链接列表,并且在将第一个节点添加到列表中时遇到了问题 . 无论出于何种原因,我的程序打印NULL,即使我将head变量引用到newNode但它不会将字符串从struct指针复制到struct指针 . 任何帮助表示赞赏 . 谢谢!

#include "stdafx.h"
#include <stdlib.h>
#include <string.h>

typedef struct stringData {
    char *s;
    struct stringData *next;
} Node;

Node *createNode(char *s) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->s = s;
    newNode->next = NULL;
    return newNode;
}


void insert(Node *head, Node *newNode) {
    if (head == NULL) {
        head->s = newNode->s;
        head = newNode;
    }
}

void printList(Node *head) {
    while (head != NULL) {
        printf("%s\n", head->s);
        head = head->next;
    }
}



int main()
{
    Node *head = createNode(NULL);

    Node *a = createNode("A");
    insert(head, a);

    printList(head);
    return 0;
}

2 回答

  • 2

    以下代码段错误:

    void insert(Node *head, Node *newNode) {...}
    ...
    insert(head, a);
    

    您需要通过引用传递指针 . 目前您正在更改本地副本(参数) .

    Fix
    将您的 insert 更改为:

    void insert(Node **head, Node *newNode) {...}
    

    并致电:

    insert(&head, a);
    

    What else
    Atleast insert (可能)更多的功能不是万无一失的(保证空指针取消引用, else 未处理的情况等) . 您需要调试并修复许多此类情况 . 在编码之前在纸上正确使用您的方法可能有所帮助

  • 0

    以下是代码的修改版本,它给出了在列表开头和列表末尾插入新节点的示例 . 实际上, insert 函数可用于在列表中的任何位置插入新节点,因为它只需要指向链接的指针和指向要插入的节点的指针 .

    #include <stdlib.h>
    #include <stdio.h>
    
    typedef struct stringData {
        char *s;
        struct stringData *next;
    } Node;
    
    Node *createNode(char *s) {
        Node *newNode = (Node *)malloc(sizeof(Node));
        newNode->s = s;
        newNode->next = NULL;
        return newNode;
    }
    
    
    void insert(Node **link, Node *newNode) {
        newNode->next = *link;
        *link = newNode;
    }
    
    void printList(Node *head) {
        while (head != NULL) {
            printf("%s\n", head->s);
            head = head->next;
        }
    }
    
    
    
    int main(void)
    {
        Node *head = NULL;
        Node *tail = NULL;
        Node *n;
    
        n = createNode("B");
        // First node at start of list - head is updated.
        insert(&head, n);
        // First node is also the tail.
        tail = n;
    
        n = createNode("A");
        // Insert node at start of list - head is updated.
        insert(&head, n);
    
        n = createNode("C");
        // Insert node at end of list.
        insert(&tail->next, n);
        // Update tail.
        tail = n;
    
        printList(head);
        return 0;
    }
    

相关问题