一个菜鸟的白痴问题。单链表
各位同为菜鸟的同学好。数据结构的作业还是要自己做的。如果不会可以像本人一样求助。但是千万不要抄袭代码。因为抄袭不会帮助你提高。而且LZ的这段代码也是作业要交的。雷同就不好了。谢谢合作。一元多项式相加。其实差不多就是单链表的合并。
编译通过。但是运行出错。
求高手解释。
#include <iostream>
using namespace std;
typedef struct LNode
{
int CCs;
int exp;
struct LNode *next;
}LNode, *Multinomial;
void CreateMultinomial(Multinomial M)
{
//创建链表
M = (Multinomial)malloc(sizeof(LNode));
M->next = NULL;
Multinomial p;
int i;
cout << "请输入多项式的项数:\n";
cin >> i;
cout << "请依次输入多项式的系数和指数:\n";
for (; i>0; i--)
{
p = (Multinomial)malloc(sizeof(LNode));
cin >> p->CCs >> p->exp;
p->next = M->next;
M->next = p;
}
}
void MergepMultinomial(Multinomial Ma, Multinomial Mb, Multinomial Mc)
{
//合并多项式
Multinomial pa = Ma->next, //报错这个指令引用的内存不能为"read".
pb = Mb->next, pc, tmpM;
Mc = (Multinomial)malloc(sizeof(LNode));
Mc->next = NULL;
int tmp;
while (pa && pb)
{
pc = (Multinomial)malloc(sizeof(LNode));
if (pa->exp == pb->exp)
{
tmp = pa->CCs + pb->CCs;
if (tmp)
{
pc->CCs = tmp;
pc->exp = pa->exp;
pc->next = Mc->next;
Mc->next = pc;
pa = pa->next;
pb = pb->next;
}
}
else if (pa->exp < pb->exp)
{
pc->CCs = pa->CCs;
pc->exp = pa->exp;
pc->next = Mc->next;
Mc->next = pc;
pa = pa->next;
}
else
{
pc->CCs = pb->CCs;
pc->exp = pb->exp;
pc->next = Mc->next;
Mc->next = pc;
pb = pb->next;
}
}
pc = (Multinomial)malloc(sizeof(LNode));
pc = tmpM = pa ? pa : pb;
while (pc->next)
pc = pc->next;
pc->next = Mc->next;
Mc->next = tmpM;
}
void OutPutMultinomial(Multinomial M)
{
//输出多项式
Multinomial p = M->next;
cout << "多项式为:\n";
while (p->next)
{
if (p->next->CCs > 0)
cout << p->CCs << "X^" << p->exp << "+";
else
cout << p->CCs << "X^" << p->exp;
p = p->next;
}
cout << p->CCs << "X^" << p->exp << endl;
}
int main()
{
Multinomial Ma, Mb, Mc;
CreateMultinomial(Ma);
CreateMultinomial(Mb);
MergepMultinomial(Ma, Mb, Mc);
OutPutMultinomial(Mc);
return 0;
}
很抱歉本人可用分为0没办法给各位加分。。希望各位高手体谅一下。。。
[ 本帖最后由 Vi_No 于 2010-3-27 01:06 编辑 ]