【发布时间】: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