數據結構 C++ 單鏈表 一元多項式的相加


#include <iostream>
using namespace std;

struct Node {
double coe; //系數
int exp; //指數
Node *next;
};

void CreatPoly(Node *&head, int n) // 生成帶表頭結點的單鏈表,除頭結點外另生成n個結點
{
head = (Node *)new Node;
head->coe = 0;
head->exp = 0;
head->next = NULL; // 初始化頭結點
cout << "分別每行輸入各項系數及指數:" << endl;
Node *p = head;
for(int i = 0; i < n; i++) {
p->next = (Node *)new Node; // 生成新結點,尾插入生成鏈表
p = p->next;
cin >> p->coe >> p->exp;
p->next = NULL;
}
}

void ShowPoly(Node *&head)
{
if(head->next == NULL) // 結果是0時直接輸出0
putchar('0');
else {
for(Node *p = head->next; p != NULL; p = p->next) {
if(p != head->next && p->coe >0) // 當p非首項且指向的系數為正時才輸出'+'
putchar('+'); // 之前只判定了p->coe >0

if(p->coe == 1) { // 系數為1或-1時特殊處理
if(p->exp == 0)
putchar('1'); // 判斷條件不能寫在一起:
} // if(p->coe == 1 && p->exp == 0) putchar('1');
else if(p->coe == -1)
putchar('-');
else
cout << p->coe;

// 指數為0或1時特殊處理
switch(p->exp) {

case 0:
break;

case 1:
putchar('x');
break;

default:
p->exp < 0 ? printf("x^(%d)", p->exp) : printf("x^%d", p->exp); // 指數小於0時打括號
break;
}
}
}
cout << endl;
}


char comp(int a, int b)
{
if(a > b)
return '>';
if(a < b)
return '<';
return '=';
}

void Free(Node *&head)
{
Node *q = NULL;
for(Node *p = head; p != NULL; p = q) {
q = p->next;
free(p);
}
}


void AddPolynomial(Node *&pA, Node *&pB) // 傳進兩個鏈表的頭指針
{
Node *ha = pA;
Node *hb = pB;
Node *qa = ha->next; // ha, hb分別跟在qa, qb的后一位置
Node *qb = hb->next; // qa, qb分別指向Pa, Pb中當前比較元素
while(qa && qb)
{
double sum = 0;
int a = qa->exp;
int b = qb->exp;
switch( comp(a, b) ) {

case '<':
ha = qa;
qa = qa->next; // 非ha = ha->next;
break;

case '=':
sum = qa->coe + qb->coe;
if(sum != 0.0) {
qa->coe = sum;
ha = qa;
}
else {
if(ha->next != qa)
cout << "Error: ha->next != qa" << endl;
ha->next = ha->next->next; // 刪除和為0的結點,ha不變,還在qa后一位置
free(qa);
}
if(hb->next != qb)
cout << "Error: hb->next != qb" << endl;
hb->next = hb->next->next;
free(qb);
qb = hb->next;
qa = ha->next;
break;

case '>':
hb->next = hb->next->next; // 刪除qb指向的結點
qb->next = ha->next; // 將qb插入ha后qa前
ha->next = qb;

qb = hb->next; // not qb = ha->next
ha = ha->next;
break;

default:
cout << "Error!" << endl;
break;
}
}
if(qb)
ha->next = qb;
free(hb);
}

void main(void)
{
Node *A = NULL;
Node *B = NULL;
int countA;
int countB;
cout << "請輸入A的項數:" << endl, cin >> countA;
CreatPoly(A, countA); // 生成A鏈表
cout << "請輸入B的項數:" << endl; // 生成B鏈表
cin >> countB;
CreatPoly(B, countB);

cout << " A = ";
ShowPoly(A);
cout << " B = ";
ShowPoly(B);

AddPolynomial(A, B); // A = A + B
cout << "A+B= ";
ShowPoly(A); // 輸出相加的和
cout << endl;
// 釋放結點
delete A;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM