多项式加法在单项链表里的表现
来源:互联网 发布:淘宝充值的钱可以退吗 编辑:程序博客网 时间:2024/06/06 02:00
输入:第一行输入m,n,用空格隔开分别代表两个多项式的项数;随后m+n行输入两个多项式的系数和指数(按照指数的降序输入),用空格隔开。
输出:两多项式的和
例:Input:2 2 Output: 2 2
2 2 4 1
1 1 2 0
3 1
2 0
代码如下:
#include <iostream>/******************************结构定义处******************************/typedef struct Lnode { int coefficient; int exponent; Lnode *next;}Lnode;/*****************************函数名:两多项式和函数输入:两无头节点链表头p1,p2。按照指数降序排列。输出:无头节点链表head,相加后的链表。*****************************/Lnode* PolyAdd(Lnode *p1, Lnode *p2){ /*头指针数据不要2*/ p1 = p1->next; p2 = p2->next; Lnode *ans, *head,*temp; ans = new Lnode; head = ans; /*防止有空的多项式2*/ if (p1 == NULL) return p2; else if (p2 == NULL) return p1; else { /*非空则进入1*/ while (p1&&p2) { temp = new Lnode; if (p1->exponent == p2->exponent) { temp->exponent = p1->exponent; temp->coeficient = p1->coeficient + p2->coeficient; ans->next = temp; p1 = p1->next; p2 = p2->next; } else if (p1->exponent>p2->exponent) { temp->coeficient = p1->coeficient; temp->exponent = p1->exponent; ans->next = temp; p1 = p1->next; } else { temp->coeficient = p2->coeficient; temp->exponent = p2->exponent; ans->next = temp; p2 = p2->next; } ans = temp; } /*一个多项式结束了,防止有另一个没有结束,将没有结束的直接传到目的指针(两个for循环)*/ for (;p1;p1 = p1->next) { temp = new Lnode; temp->coeficient = p1->coeficient; temp->exponent = p1->exponent; ans->next = temp; ans = temp; } for (;p2;p2 = p2->next) { temp = new Lnode; temp->coeficient = p2->coeficient; temp->exponent = p2->exponent; ans->next = temp; ans = temp; } ans->next = 0; return head; }}/************************函数名:创建多项式链表函数输入:多项式项数输出:无头节点链表head,创建的链表头。************************/Lnode* CreatLnode(int n){ Lnode *p,*q,*head; p = new Lnode; head = p; while(n--){ q = new Lnode; std::cin>>q->coefficient>>q->expoent; p->next = q; p = q; } p->next = 0; return head;}/************************函数名:输出多项式链表函数输入:头指针输出:去掉头指针的所有项************************/void printLnode(Lnode* p){ p = p->next; while (p) { std::cout << p->coefficient << " " << p->exponent<<std::endl; p = p->next; }}/************************函数名:主函数************************/int main() { Lnode *p1, *p2, *ans; int l1, l2; int* x, y; std::cin >> l1 >> l2; p1 = CreatLnode(l1); p2 = CreatLnode(l2); ans = PolyAdd(p1, p2); printLnode(ans); system("pause"); return 0;}
阅读全文
0 0
- 多项式加法在单项链表里的表现
- 一元多项式的乘法与加法运算【Java实现--通过单项链表实现队列】
- 多项式的加法
- 两个多项式的加法
- 多项式的加法
- 多项式加法的实现
- 在无头节点的单链表里删除元素
- 单链表表示多项式ADT&多项式加法
- 链表的多项式加法链表的多项式加法
- 一元多项式的加法C++
- 多项式加法的Java实现
- 多项式的加法乘法实现
- 多项式的加法与乘法
- 多项式的加法和乘法
- 单项链表的建立
- 单项链表的反转
- 单项链表的实现
- 多项式加法
- JavaSwing 贪吃蛇
- Qt学习之2D绘图(画刷和画笔)
- Application
- 哈希算法的简单加密程序
- PHP 1 PHP的基本语法
- 多项式加法在单项链表里的表现
- 题目1475:IP数据包解析
- 安卓手机数据备份与恢复方法汇总和操作详解
- 洛谷P3216 [HNOI2011]数学作业
- 关于前面二维码生成类字数限制的修改
- Java 关于继承中的static代码块,普通代码块及构造方法的执行顺序
- JStorm与Storm源码分析(三)--Scheduler,调度器
- python字符串截取操作
- 公司清算案件的诉讼费收取问题