這篇文章給大家介紹怎么在C語言中實(shí)現(xiàn)多項(xiàng)式相加,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序設(shè)計(jì)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了云州免費(fèi)建站歡迎大家使用!
C語言是一門面向過程的、抽象化的通用程序設(shè)計(jì)語言,廣泛應(yīng)用于底層開發(fā),使用C語言可以以簡(jiǎn)易的方式編譯、處理低級(jí)存儲(chǔ)器。
包含帶頭節(jié)點(diǎn)的鏈表的初始化,輸出:
#define _CRT_SECURE_NO_WARNINGS #include#include typedef struct Pol { int coe; // 系數(shù) int index; // 指數(shù) struct Pol *next; }Pol; int main(int argc, char *argv[]) { Pol *head1 = NULL; // 第一個(gè)多項(xiàng)式 Pol *head2 = NULL; // 第二個(gè)多項(xiàng)式 Pol *Initiate(Pol *head1); // 聲明初始化函數(shù) void Output(Pol *head); // 聲明輸出函數(shù) void PolAdd(Pol *head1, Pol *head2); // 聲明相加函數(shù) int coe, index; char sign; Pol *p; int n = 0; // 初始化第一個(gè)多項(xiàng)式 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("第一多項(xiàng)式輸入完畢。\n"); // 初始化第二個(gè)多項(xiàng)式 head2 = Initiate(head2); p = head2; 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("第二多項(xiàng)式輸入完畢。\n"); // 調(diào)用相加函數(shù)和輸出函數(shù) PolAdd(head1, head2); Output(head1); system("PAUSE"); return 0; } // 初始化鏈表函數(shù) Pol *Initiate(Pol *head) { head = (Pol *)malloc(sizeof(Pol)); head->next = NULL; return head; } // 初始化相加函數(shù) 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; // 刪除節(jié)點(diǎn) 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; } } // 兩串長(zhǎng)度不相等時(shí),把尾部一次加入 if (p != NULL) pre->next = p; else pre->next = q; } // 輸出函數(shù) 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->coe, p->index); p = p->next; } i++; } }
關(guān)于怎么在C語言中實(shí)現(xiàn)多項(xiàng)式相加就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。