【问题标题】:array to linked list function in C; how to iterate over list to attach the node?C中的数组到链表函数;如何遍历列表以附加节点?
【发布时间】:2019-11-20 12:11:52
【问题描述】:

我正在构建一些基本上会接收一个数组的代码,并以相同的顺序返回一个链表。我被困在没有出路的条件下。如何将温度附加到节点?我知道我必须遍历 ->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;
} 

【问题讨论】:

  • 你的函数应该返回一个指针。它被定义为返回一个node,在实践中,它返回nothing

标签: c arrays linked-list


【解决方案1】:

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

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;

【讨论】:

  • 谢谢!我喜欢创造性的解决方案。另外,您能否指出我的代码中出了什么问题?这可能是我声明 ListNode temp 的时候,但我不知道如何解决它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 2012-10-05
  • 2012-03-25
  • 2018-10-28
  • 1970-01-01
相关资源
最近更新 更多