数据结构学习之路5 队列的应用——多项式相加

来源:互联网 发布:淘宝不能搜索 编辑:程序博客网 时间:2024/06/11 04:05

此次代码不支持键盘输入两个待加的多项式,需要在程序内部设定两个多项式,然后计算他们的和,用到的数据结构是链表形式的队列

代码如下

#include<iostream>using namespace std;typedef struct Qnode *Queue;struct Qnode{int xishu;int zhishu;Queue next;};int Compare(int a, int b){if(a > b)return 1;else if(b > a)return -1;else return 0;}void Attach(int a, int b, Queue *p){Queue s;s = (Queue)malloc(sizeof(Qnode));s ->xishu = a;s ->zhishu = b;s ->next = NULL;(*p) ->next = s;*p = s;}Queue creat(){Queue p;p = (Queue)malloc(sizeof(Qnode));p ->next = NULL;return p;}Queue addQ(Queue p1, Queue p2){Queue front, rear, temp;front = rear = (Queue)malloc(sizeof(Qnode));while(p1 && p2){switch(Compare(p1 ->zhishu, p2 ->zhishu)){case 1:Attach(p1 ->xishu, p1 ->zhishu, &rear);p1 = p1 ->next;break;case -1:Attach(p2 ->xishu, p2 ->zhishu, &rear);p2 = p2 ->next;break;case 0:int a = p1 ->xishu + p2 ->xishu;if(a)Attach(a, p1 ->zhishu, &rear);p1 = p1 ->next;p2 = p2 ->next;break;}}for(; p1; p1 = p1 ->next) Attach(p1 ->xishu, p1 ->zhishu, &rear);for(; p2; p2 = p2 ->next) Attach(p2 ->xishu, p2 ->zhishu, &rear);temp = front;front = front ->next;free(temp);return front;}void add(int a, int b, Queue p){Queue s;s = (Queue)malloc(sizeof(Qnode));s ->xishu = a;s ->zhishu = b;s ->next =NULL;while(p ->next != NULL){p = p ->next;}p ->next = s;}void show(Queue p){if(p ->next == NULL)return;p = p ->next;for(int i = 0;p ->next != NULL;p = p ->next){i ++;if(p ->xishu > 0 && i != 1)cout << "+";cout << p ->xishu << "x" << "^" << p ->zhishu;}if(p ->xishu > 0)cout << "+";cout << p ->xishu << "x" << "^" << p ->zhishu << endl;}void main(){Queue p1 = creat();Queue p2 = creat();add(2, 5, p1);add(-1, 3, p1);add(3, 2, p1);add(4, 1, p1);add(7, 0, p1);show(p1);add(2, 5, p2);add(5, 4, p2);add(3, 3, p2);add(5, 2, p2);add(2, 0, p2);show(p2);Queue result = addQ(p1, p2);show(result);system("pause");}


阅读全文
0 0
原创粉丝点击