【发布时间】:2020-08-22 01:02:26
【问题描述】:
嘿,我尝试构建一个链表,我构建了两个函数,一个用于插入,一个用于创建列表 但我在插入时有问题我认为是内存问题 我找不到 代码正在运行,但有时它会无缘无故地跳转到另一个函数,但我不知道为什么
感谢任何帮助/想法
#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
typedef struct {
int num;
struct List* next;
}List;
// i think the problem is in here cant find it :(((
List* insert(List* head, int num)
{
List* temp = (List*)malloc(sizeof(List));
List* temp_head = head;
temp->num = num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
}
else
{
while (temp_head->next != NULL)
{
temp_head = temp_head->next;
}
temp_head->next = temp;
}
return head;
}
List* create_new_list(List* new_list)
{
int number;
printf("Enter numbers, to exit enter negative number\n");
scanf_s("%d", &number);
if (number <= 0)
{
return NULL;
}
new_list->num = number;
new_list->next = NULL;
scanf_s("%d", &number);
while (number >= 0)
{
new_list=insert(new_list, number);
scanf_s("%d", &number);
}
return new_list;
}
int main()
{
List* head= (List*)malloc(sizeof(List));
head=create_new_list(head);
}
【问题讨论】:
-
list* head = (list*)malloc(sizeof(list));->list *head = malloc (sizeof(List));(注意List中的'L',或者更好的list *head = malloc (sizeof *head);甚至更好,你不需要分配给list,例如@ 987654331@ 和 C 中,malloc的返回不需要强制转换,没有必要。见:Do I cast the result of malloc? -
您还可以找到(按顺序)Singly Linked List (node only, no wrapper),然后使用包装器为 O(1) 插入提供
tail指针 Singly Linked List of Integers (example) -
好的,我尝试制作 *head=NULL 但也没有帮助为什么 head=create_new_list(&head);?
-
最大的问题在于
(list*)malloc(sizeof(list));而不是(list*)malloc(sizeof(List));,当然还有list* head->List* head和list* insert(list* head, int num)->List* insert(List* head, int num)。 检查你的 L's. -
好的,我试过但没有帮助://
标签: c memory linked-list