【问题标题】:C: From char array to linked listC:从char数组到链表
【发布时间】:2020-08-26 08:03:07
【问题描述】:

我仍在学习如何用 C 编程,但我偶然发现了一个问题。 使用 char 数组,我需要创建一个链表,但我不知道该怎么做。我在网上搜索过,但似乎很混乱。 char 数组是这样的 char arr[3][2]={"1A","2B","3C"};

【问题讨论】:

  • 你熟悉链表吗?你知道如何自己实现吗? (不考虑数组)
  • 查看this 教程,并在node 结构中将int 替换为char[2]

标签: c arrays linked-list char


【解决方案1】:

看看下面的这段代码。它使用Node 结构,您可以看到我们如何遍历列表、创建节点、分配内存并将它们添加到链表中。它基于thisGeeksForGeeks 文章,做了一些修改。我建议您比较两者以帮助了解发生了什么。

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

struct Node {
        char value[2];
        struct Node * next;
};

int main() {

        char arr[3][2] = {"1A","2B","3C"};

        struct Node * linked_list = NULL;

        // Iterate over array
        // We calculate the size of the array by using sizeof the whole array and dividing it by the sizeof the first element of the array
        for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
                // We create a new node
                struct Node * new_node = (struct Node *)malloc(sizeof(struct Node));
                // Assign the value, you can't assign arrays so we do each char individually or use strcpy
                new_node->value[0] = arr[i][0];
                new_node->value[1] = arr[i][1];
                // Set next node to NULL
                new_node->next = NULL;

                if (linked_list == NULL) {
                        // If the linked_list is empty, this is the first node, add it to the front
                        linked_list = new_node;
                        continue;
                }

                // Find the last node (where next is NULL) and set the next value to the newly created node
                struct Node * last = linked_list;
                while (last->next != NULL) {
                        last = last->next;
                }
                last->next = new_node;
        }

        // Iterate through our linked list printing each value
        struct Node * pointer = linked_list;
        while (pointer != NULL) {
                printf("%s\n", pointer->value);
                pointer = pointer->next;
        }

        return 0;
}

上面的代码缺少一些东西,比如检查每个malloc是否成功,以及free之后分配的内存。这只是为了给你一些可以建立的东西!

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2020-04-25
    • 1970-01-01
    • 2013-06-02
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多