链表应用 多项式相加
生活随笔
收集整理的這篇文章主要介紹了
链表应用 多项式相加
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?用鏈表實現多項式相加
#include<iostream> #include<cstdio> #include<malloc.h> #define flag -1 using namespace std; typedef struct Node {float coef;int expn;struct Node *next; }LNode,*LinkList;void CreatLinkList(LinkList L) {LNode *r,*s;float x;int y;scanf("%f%d",&x,&y);r=L;while(y!=0){s=(LinkList)malloc(sizeof(LNode));s->coef=x;s->expn=y;r->next=s;r=s;scanf("%f%d",&x,&y);}r->next=NULL;} LinkList Add_L(LinkList P,LinkList Q) {LNode *p,*q;LNode *r,*s;float sum;p=P->next;q=Q->next;r=P;while(p&&q){if((p->expn)<(q->expn)){r->next=p;r=r->next;p=p->next;}else if((p->expn)>(q->expn)){r->next=q;r=r->next;q=q->next;}else {sum=(p->coef)+(q->coef);if(sum!=0){(p->coef)=sum;r->next=p;r=r->next;p=p->next;s=q;q=q->next;free(s); }else{s=p;p=p->next;free(s);s=q;q=q->next;free(s);} }}if(p)r->next=p;elser->next=q;free(Q);return P; }void DisPlay(LinkList L) {LinkList p=NULL;p=L->next;while(p!=NULL){printf("(%f,%d)",p->coef,p->expn);p=p->next;}cout<<endl; }int main() {LinkList L1,L2;L1=(LinkList)malloc(sizeof(LNode));L1->next=NULL;L2=(LinkList)malloc(sizeof(LNode));L2->next=NULL;cout<<"input L1"<<endl;cout<<"請輸入L1的多個系數and指數,0 0結束"<<endl;cout<<"舉個栗子:1^1+2^2+3^3輸入為1 1 2 2 3 3 0 0回車"<<endl;CreatLinkList(L1);cout<<"input L2"<<endl;cout<<"請輸入L1的多個系數and指數,0 0結束"<<endl;CreatLinkList(L2);LinkList t=Add_L(L1,L2);cout<<"相加后"<<endl;DisPlay(t);cout<<endl;}?
?
?
?
?
總結
以上是生活随笔為你收集整理的链表应用 多项式相加的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab weibpdf函数,mat
- 下一篇: python中getopt函数_Pyth