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

时间:2019-07-10 20:10:14

标签: c arrays linked-list

我正在构造一些代码,这些代码基本上会占用错误,并以相同的顺序返回链接列表。我陷入了一个没有条件的条件。如何将临时节点附加到节点?我知道我必须遍历->下一步,直到其不为null为止,但我不知道怎么做。

#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;
} 

1 个答案:

答案 0 :(得分:3)

如果您向后执行列表,则根本不需要遍历列表:

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;