c - 数组到 C 中的链表函数;如何遍历列表以附加节点?

标签 c arrays linked-list

我正在构建一些代码,这些代码基本上接受一个数组,并以相同的顺序返回一个链表。我被困在一个没有出路的条件中。如何将临时文件附加到节点?我知道我必须遍历 ->next 直到它不为空,但我不知道该怎么做。

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


struct ListNode{

    int data;
    struct ListNode* next;

};

struct ListNode populateLinkedList(int arr[], int arraysize){
    struct ListNode* head = NULL;
    struct ListNode* lastNodePtr = NULL;
    struct ListNode* node = NULL;

    for(int i=0; i<arraysize; i++){

        struct ListNode* tempNodePtr = (struct ListNode*) malloc(sizeof(struct ListNode));
        tempNodePtr->data = arr[i];
        tempNodePtr->next = NULL;

        //if header is empty assign new node to header
        if(head==NULL) {
            head = tempNodePtr;
        }
            //if the temp node is empty assign new node to temp node
        else if(node==NULL) {
            node = tempNodePtr;
        }
            //if both header and temp node are not empty, attach the temp to node. This is where I get an error.
        else {
            struct ListNode* temp = *node->next;
            while (temp!=NULL){
                temp = temp->next;
            }
            temp->next = tempNodePtr;
            node->next = temp;

        }
    }

    //connect head with nodes after index 0
    head->next = node;
    return head
}

int main() {
    printf("Entering program 2\n");

    int array[] = {5,8,2,4,12,97,25,66};
    int arraysize = (int)( sizeof(array) / sizeof(array[0]));
    printf("mainSize: %d \n", arraysize);

    populateLinkedList(array, arraysize);
    return 0;
} 

最佳答案

如果你向后做,你根本不需要遍历列表:

struct ListNode* populateLinkedList(int arr[], int arraysize) {
    struct ListNode* head = NULL;
    for (int i = arraysize; i > 0; i--) {
        struct ListNode* tempNodePtr = (struct ListNode*) malloc(sizeof(*tempNodePtr));
        tempNodePtr->data = arr[i - 1];
        tempNodePtr->next = head;
        head = tempNodePtr;
    }
    return head;
}

如您所见,这要简单得多,因为没有检查,因为您总是替换 head 并且不需要迭代已经插入的元素,因此它也更有效。


至于你的解决方案有什么问题:

struct ListNode* temp = *node->next;
//                      ^~~~~~~~~~~
// you definitely shouldn't dereferrence anything here

// This condition is wrong because when you exit the loop "temp" will be NULL
while (temp!=NULL) {
    temp = temp->next;
}
temp->next = tempNodePtr;
node->next = temp; // <-- this is definitely not needed

所以你的代码应该是这样的:

struct ListNode* temp = node;
while (temp->next != NULL) {
    temp = temp->next;
}
temp->next = tempNodePtr;

关于c - 数组到 C 中的链表函数;如何遍历列表以附加节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56977942/

相关文章:

c - 我可以使用哪些免费工具来分析 Windows 上的 C 代码?

arrays - 无法分配给数组 -vba

c++ - 在链接列表中使用 C++ 模板,列表中出现多种不同类型

c - 为什么这段代码会产生段错误?

java - 如何测试并查看 String[] 中的所有内容是否都在 ArrayList<String> 中

java - 循环单链表

c - C中的正则表达式匹配

c - 编码维吉尼亚密码时c中的段错误

任何人都可以帮我调试这段代码,因为它在中间停止工作

python - Cython 初学者 - 加速 numpy 广播