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