//多项式ADT
//利用单链表实现
//要求:输入顺序必须按照从指数的大小,由大到小
//如:7x^3+4x^2+1
//想要结束该次多项式输入,请在下一项输入 0 -1
#include<stdlib.h>
#include<iostream>
typedef struct node *ptrNode;
#define Len sizeof(struct node)
struct node
{
int coefficient;
int exponent;
ptrNode next;
};
typedef ptrNode polynomial;
int max(const int x,const int y)
{
if (x >= y)
return x;
else
return y;
}
//找到最高指数项
polynomial find(polynomial poly)
{
polynomial p = poly;
if (p->next == nullptr)
return p;
else
{
do
{
p = p->next;
} while (p->next!=nullptr);
return p;
}
}
//逆向计算出sum
polynomial add(polynomial poly1, polynomial poly2)
{
polynomial p1 = poly1; polynomial p2 = poly2;
polynomial head=nullptr,p;
int max_expo = max((find(p1)->exponent), (find(p2)->exponent));
p = (polynomial)malloc(Len);
p->next = nullptr;
p->exponent = 0;
while (p->exponent<=max_expo)
{
if (p1 == nullptr && p2 == nullptr) break;
if ((p1 != nullptr) && (p2 != nullptr))
{
if (p1->exponent == p2->exponent)
{
p->exponent = p1->exponent;
p->coefficient = p1->coefficient + p2->coefficient;
head = p;
p1 = p1->next;
p2 = p2->next;
}
else if (p1->exponent<p2->exponent)
{
p->exponent = p1->exponent;
p->coefficient = p1->coefficient;
head = p;
p1 = p1->next;
}
else
{
p->exponent = p2->exponent;
p->coefficient = p2->coefficient;
head = p;
p2 = p2->next;
}
}
else if (p1 == nullptr)
{
p->exponent = p2->exponent;
p->coefficient = p2->coefficient;
head = p;
p2 = p2->next;
}
else
{
p->exponent = p1->exponent;
p->coefficient = p1->coefficient;
head = p;
p1 = p1->next;
}
p = (polynomial)malloc(Len);
p->next = head;
}
return head;
}
//倒挂式建立链表
polynomial create()
{
polynomial head, p1;
p1 = (polynomial)malloc(Len);
std::cout << "第1项:(如3x^4,输入3 4)" << std::endl;
std::cin >> p1->coefficient >> p1->exponent;
p1->next = nullptr;
head = p1;
int n = 1;
while (p1->exponent != -1)
{
p1 = (polynomial)malloc(Len);
p1->next = head;
std::cout <<"第"<<++n<<"项:"<< std::endl;
std::cin >> p1->coefficient >> p1->exponent;
head = p1;
}
return head->next;
}
void print(polynomial poly)
{
polynomial p= poly;
while ((p->next)!= nullptr)
{
std::cout << p->coefficient << "x^" << p->exponent << "+";
p = p->next;
}
std::cout << p->coefficient << "x^" << p->exponent;
}
int main()
{
std::cout << "请输入第1个表达式:(0 -1结束)" << std::endl;
polynomial poly1 = create();
std::cout << "请输入第2个表达式:" << std::endl;
polynomial poly2 = create();
polynomial polySum=add(poly1, poly2);
std::cout << "the sum=";
print(polySum);
std::cout << std::endl;
return 0;
}
使用单链表编的多项式,因为语言掌握不好,C和Cpp混用。另外输入的格式要求严格,没检查特殊情况是否正确。
学习单链表的一个例子,供参考。