链表分配内存失败,求原因……
程序代码:#include <stdio.h>
#include <stdlib.h>
#define MallocMemory (Nape *)malloc(sizeof(Nape))
typedef struct Nape Nape;
struct Nape //定义多项式链表
{
int Factor; //系数
int Index; //指数
struct Nape *next;
};
Nape *IniNape(Nape *h); //输入函数链表
void ShowNape(Nape *h); //输出函数链表
Nape *AddNape(Nape *h1, Nape *h2); //多项式相加
int main()
{
/*定义3个函数 Func是Function(函数)的缩写*/
Nape *Func1 = NULL, *Func2 = NULL, *Func3 = NULL;
Func1 = IniNape(Func1);
Func2 = IniNape(Func2);
getchar();
Func3 = AddNape(Func1, Func2); //多项式相加
ShowNape(Func3);
return 0;
}
//*********定义输入链表函数*********
Nape *IniNape(Nape *h)
{
Nape *temp1, *temp2;
temp1 = temp2 = MallocMemory;
printf("请输入系数:");
scanf("%d", &temp2->Factor);
printf("请输入指数:");
scanf("%d", &temp2->Index);
temp2->next = NULL;
while (temp2->Factor != 100)
{
if (h == NULL)
{
h = temp2;
}
else
{
temp1->next = temp2;
}
temp1 = temp2;
temp2 = MallocMemory;
if (temp2 != NULL)
{
int i = 0;
printf("请输入系数(若输入100),结束输入:");
scanf("%d", &i);
if(i == 100)
{
temp2 = NULL;
break;
}
else
{
temp2->Factor = i;
printf("请输入指数:");
scanf("%d", &temp2->Index);
temp2->next = NULL;
}
}
}
fflush(stdin);
printf("\n\n输入完毕!你输入的多项式为:\n\n");
ShowNape(h);
printf("\n\n");
return h;
}
//***********输出链表函数*************
void ShowNape(Nape *h)
{
Nape *temp = h;
printf("%d(X)^%d", temp->Factor, temp->Index);
temp = temp->next;
while (temp != NULL)
{
if(temp->Factor > 0)
{
putchar('+');
}
printf("%d(X)^%d", temp->Factor, temp->Index);
temp = temp->next;
}
}
//*************多项式相加*************
Nape *AddNape(Nape *h1, Nape *h2)
{
int flag = 0;
Nape *temp1 = h1, *temp2 = h2, *head = NULL, *temp3;
system("cls");
printf("\n\n\n多项式相加\n\n\n");
/*先把h1链表完整的复制到head中*/
head = temp3 = MallocMemory;
while (1)
{
temp3->Factor = temp1->Factor;
temp3->Index = temp1->Index;
if(temp1->next != NULL)
{
temp3->next = MallocMemory;
temp3 = temp3->next;
temp1 = temp1->next;
}
else
{
temp3->next = NULL;
break;
}
}
while (temp2 != NULL)
{
flag = 0;
temp3 = head;
while (temp3 != NULL)
{
if (temp3->Index == temp2->Index)
{
temp3->Factor += temp2->Factor;
temp3 = temp3->next;
temp2 = temp2->next;
flag = 1;
break;
}
else
{
temp3 = temp3->next;
}
}//while (temp3 != NULL)结束
//如果没有找到,则复制到表尾
if (flag == 0)
{
if((temp3 = MallocMemory) == NULL);
{
printf("内存分配失败!\n\n");
getchar();
exit(0);
}
temp3->Factor = temp2->Factor;
temp3->Index = temp2->Index;
temp3->next = NULL;
temp2 = temp2->next;
}
}//while (temp2 != NULL) 结束*/
return head;
}
==========================================================此程序是把两个一元多项式相加起来,假设我们输入第一元多项式为 2x^3+4x^5,第二个元多项式为 3x^4,那么在运行的时候会出项:“分配内存失败”的现象,请问为什么会“分配内存失败”,怎么修改?










