标签:
1 #include <iostream> 2 #include<stdlib.h> 3 4 using namespace std; 5 6 typedef struct LNode 7 { 8 int coef;//系数 9 int expn;//指数 10 struct LNode *next; 11 }LNode,*LinkList; 12 13 14 int CreateList_L(LinkList &L,int n) 15 { 16 LinkList p,q; 17 for(int i=0;i<n;i++) 18 { 19 p=(LinkList)malloc(sizeof(LNode)); 20 cout<<"输入元素系数:"; 21 cin>>p->coef; 22 cout<<"输入元素指数:"; 23 cin>>p->expn; 24 if(i==0)L=p; 25 else q->next=p; 26 q=p; 27 p->next=NULL; 28 } 29 return 0; 30 } 31 32 33 int Display_L(LinkList L) 34 { 35 cout<<"f(x)="<<L->coef; 36 if(L->expn)cout<<"*"<<"x^"<<L->expn; 37 L=L->next; 38 while(L) 39 { 40 if(L->coef>0) 41 { 42 cout<<"+"; 43 cout<<L->coef<<"*"<<"x^"<<L->expn; 44 } 45 else cout<<L->coef<<"*"<<"x^"<<L->expn; 46 L=L->next; 47 } 48 return 0; 49 } 50 51 52 int AddPolyn(LinkList &La,LinkList &Lb,LinkList &Lc) 53 { 54 LinkList pa,pb,p; 55 int k=1; 56 pa=La;pb=Lb; 57 while(k)//确定“和多项式”的头结点 58 { 59 if(pa->expn<pb->expn){p=Lc=pa;pa=pa->next;k=0;} 60 else if(pa->expn>pb->expn){p=Lc=pb;pb=pb->next;k=0;} 61 else 62 { 63 pa->coef+=pb->coef; 64 if(pa->coef) 65 { 66 p=Lc=pa; 67 pa=pa->next; 68 k=0; 69 } 70 else 71 { 72 pa=pa->next; 73 pb=pb->next; 74 } 75 } 76 } 77 78 79 while(pa&&pb) 80 { 81 if(pa->expn<pb->expn){p->next=pa;p=pa;pa=pa->next;} 82 else if(pa->expn>pb->expn){p->next=pb;p=pb;pb=pb->next;} 83 else 84 { 85 pa->coef+=pb->coef; 86 if(pa->coef) 87 { 88 p->next=pa; 89 p=pa; 90 pa=pa->next; 91 pb=pb->next; 92 } 93 else 94 { 95 pa=pa->next; 96 pb=pb->next; 97 } 98 99 } 100 } 101 while(!pb&&pa) 102 { 103 p->next=pa; 104 p=pa; 105 pa=pa->next; 106 } 107 while(!pa&&pb) 108 { 109 p->next=pb; 110 p=pb; 111 pb=pb->next; 112 } 113 return 0; 114 } 115 116 117 118 int main() 119 { 120 LinkList La,Lb,Lc; 121 int m,n; 122 cout<<"请输入La中的元素个数:"; 123 cin>>m; 124 CreateList_L(La,m); 125 cout<<"请输入Lb中的元素个数:"; 126 cin>>n; 127 CreateList_L(Lb,n); 128 AddPolyn(La,Lb,Lc); 129 Display_L(Lc); 130 return 0; 131 }
标签:
原文地址:http://www.cnblogs.com/journal-of-xjx/p/5901469.html