1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
| #include<iostream> using namespace std;
typedef struct LinkNode { int cofe; int exp; struct LinkNode* next; }LinkList,LinkNode;
void initLinkList(LinkList*& L) { L = new LinkList; L->next = NULL; }
void LinkPushBack(LinkList* L, int _cofe, int _exp) { LinkNode* node = new LinkNode; node->cofe = _cofe; node->exp = _exp;
LinkNode* temp = L; while (temp->next) { temp = temp->next; } temp->next = node; node->next = NULL; }
void inputPoly(LinkList* L1, LinkList* L2) { int l1cofe = 0; int l2cofe = 0; int l1exp = 0; int l2exp = 0;
int l1num = 0; int l2num = 0;
cout << "第一个多项式有几项?" << endl; cin >> l1num; for (int i = 0; i < l1num; i++) { cout << "请输入第"<<i+1<<"项的系数:" << endl; cin >> l1cofe; cout << "请输入第" << i+1 << "项的次方:" << endl; cin >> l1exp; LinkPushBack(L1, l1cofe, l1exp); } cout << "第一个多项式输入完毕!" << endl;
cout << "第二个多项式有几项?" << endl; cin >> l2num; for (int i = 0; i < l2num; i++) { cout << "请输入第" << i+1<< "项的系数:" << endl; cin >> l2cofe; cout << "请输入第" << i+1 << "项的次方:" << endl; cin >> l2exp; LinkPushBack(L2, l2cofe, l2exp); } cout << "第二个多项式输入完毕!" << endl; cout << "多项式输入完毕!" << endl; }
void sumList(LinkList* L1, LinkList* L2) { LinkNode* p = L1->next; LinkNode* q = L2->next; LinkNode* pFront = L1; LinkNode* qFront = L2;
while (q && p) { if (p->exp == q->exp) { p->cofe += q->cofe; LinkNode* temp = new LinkNode; temp = q; qFront->next = temp->next; delete temp;
pFront = p; p = p->next;
q = qFront->next; } else if(p->exp < q->exp) { pFront = p; p = p->next; } else if(p->exp > q->exp) {
qFront->next = q->next; pFront->next = q; q->next = p; q = qFront->next; pFront = pFront->next; } } if (q) { while (q) { pFront->next = q; pFront = pFront->next; q = q->next; } pFront->next = NULL; } L2->next = NULL;
cout << "相加结果为:" << endl; L1 = L1->next; while (L1) { cout << "(" << L1->cofe << "," << L1->exp << ")" << " "; L1 = L1->next; } }
void destoryLink(LinkNode*& L) { LinkNode* tempNode = L; while (tempNode) { L = L->next; delete tempNode; tempNode = L; } } int main(void) { LinkList* L1; LinkList* L2; initLinkList(L1); initLinkList(L2); inputPoly(L1, L2); sumList(L1, L2) ;
destoryLink(L1); destoryLink(L2);
return 0; }
|