【发布时间】:2016-10-11 13:39:01
【问题描述】:
typedef struct node
{
int a;
struct node *next;
}node;
void generate(struct node **head)
{
int num = 10, i; //the num here is the length
struct node *temp;
for (i = 0; i < num; i++)
{
temp = (struct node*)malloc(sizeof(struct node));
temp->a = 10-i;
if (*head == NULL)
{
*head = temp; //each time add another node to the start
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}
void addSpecific(node* head,int n)
{
node* temp = NULL;
if (head->next == NULL)
{
temp = (node*)malloc(sizeof(node*)); //allocating memory
(temp)->a = n; //adding the wanted value
(temp)->next = NULL; //making the new node to point to the end
head->next = temp; //and the previous one to point to temp
}
else
{
addSpecific(head->next, n); //if this is not the wanted node we need to move to the next node
}
}
void deleteNode(struct node **head)
{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next; //going to the next node
free(temp); //free the allocated memory
}
}
int main()
{
struct node *head = NULL;
generate(&head);
addSpecific(head, 7);
display(head);
deleteNode(&head);
system("PAUSE");
return 0;
}
我试图在末尾使用递归插入新节点,但是空闲内存(删除)函数进行了扩展,我找不到问题。我尝试了生成函数并在最后添加节点,它工作但编译器提醒我“堆损坏”。
【问题讨论】:
-
分配
head->next = &temp并没有按照您的想法进行。如果您没有从该行收到编译器警告,则需要启用更多警告。至于为什么错了,想想head->next是什么类型,temp是什么类型,最后&temp是什么类型? -
没有直接关系,但在这里使用递归是个糟糕的主意。
-
老师告诉我的,我别无选择
-
也不相关:不要写
(temp)->a,你应该写temp->a,这样更标准,纯粹是装饰性的,生成的代码是一样的。 -
想想如果列表有几千个节点会发生什么......所有普通的标准计算机和编译器都使用堆栈进行函数调用,并且堆栈是有限的资源(Windows 上的默认堆栈大小使用 Visual Studio 编译器是一个兆字节)。
标签: c pointers recursion linked-list singly-linked-list