单向链表为什么会有内存错误。 还有凡是用malloc开辟的空间 一定要用free函数释放吗?
#include <stdio.h>#include <malloc.h>
#include <conio.h>
struct LNode
{
int data;
struct LNode *next;
};
struct LNode *create(int n)
{
int i;
struct LNode *head, *p1, *p2;
int a;
head = NULL;
printf("Input the integers:\n");
for(i = n; i > 0; i--)
{
p1 = (struct LNode*)malloc(sizeof(struct LNode));
scanf("%d", &a);
p1->data = a;
if (head = NULL)
{
head = p1;
p2 = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
}
p2->next = NULL;
return head;
}
void main()
{
int n;
struct LNode *q;
printf("Inout the count of the nodes you want to create:\n");
scanf("%d", &n);
q = create(n);
printf("the result is :\n");
while(q)
{
printf("%d ", q->data);
q = q->next;
}
getch();
}
[ 本帖最后由 waja 于 2013-3-10 09:19 编辑 ]