C語言實現多項式的相加
阿新 • • 發佈:2020-01-07
本文例項為大家分享了C語言多項式相加的具體程式碼,供大家參考,具體內容如下
包含帶頭節點的連結串列的初始化,輸出:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef struct Pol { int coe; // 係數 int index; // 指數 struct Pol *next; }Pol; int main(int argc,char *argv[]) { Pol *head1 = NULL; // 第一個多項式 Pol *head2 = NULL; // 第二個多項式 Pol *Initiate(Pol *head1); // 宣告初始化函式 void Output(Pol *head); // 宣告輸出函式 void PolAdd(Pol *head1,Pol *head2); // 宣告相加函式 int coe,index; char sign; Pol *p; int n = 0; // 初始化第一個多項式 head1 = Initiate(head1); p = head1; while (1) { scanf("%dx%d%c",&coe,&index,&sign); p->next = (Pol *)malloc(sizeof(Pol)); p = p->next; p->coe = coe; p->index = index; p->next = NULL; if(sign == '\n') break; } printf("第一多項式輸入完畢。\n"); // 初始化第二個多項式 head2 = Initiate(head2); p = head2; while (1) { scanf("%dx%d%c",&sign); p->next = (Pol *)malloc(sizeof(Pol)); p = p->next; p->coe = coe; p->index = index; p->next = NULL; if (sign == '\n') break; } printf("第二多項式輸入完畢。\n"); // 呼叫相加函式和輸出函式 PolAdd(head1,head2); Output(head1); system("PAUSE"); return 0; } // 初始化連結串列函式 Pol *Initiate(Pol *head) { head = (Pol *)malloc(sizeof(Pol)); head->next = NULL; return head; } // 初始化相加函式 void PolAdd(Pol *head1,Pol *head2) { Pol *p = head1->next; Pol *q = head2->next; Pol *pre = head1; Pol *temp = NULL; int sum; while ((p != NULL) && (q != NULL)) { if (p->index < q->index) { pre->next = p; pre = pre->next; p = p->next; } else if(p->index == q->index) { sum = p->coe + q->coe; if (sum != 0) { p->coe = sum; pre->next = p; pre = pre->next; p = p->next; // 刪除節點 temp = q; q = q->next; free(temp); } else { temp = p; p = p->next; free(temp); temp = q; q = q->next; free(temp); } } else { pre->next = q; pre = pre->next; q = q->next; } } // 兩串長度不相等時,把尾部一次加入 if (p != NULL) pre->next = p; else pre->next = q; } // 輸出函式 void Output(Pol *head) { Pol *p = head; p = p->next; int i = 0; while (p) { if (p->coe > 0 && i != 0) { printf("+%dX^%d",p->coe,p->index); p = p->next; } else { printf("%dX^%d",p->index); p = p->next; } i++; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。