資料結構之---C語言實現連式多項式,---c多項式

來源:互聯網
上載者:User

資料結構之---C語言實現連式多項式,---c多項式

//鏈式儲存實現多項式#include <stdio.h>#include <stdlib.h>typedef struct term *link;struct term {int c;//係數int e;//指數link next;};typedef struct{link head;//頭指標link tail;//尾指標}*poly_t;link TERM(int c, int e){link t = malloc(sizeof *t);t->c = c;t->e = e;t->next = NULL;return t;}poly_t poly_init(){poly_t p = malloc(sizeof *p);p->head = p->tail = TERM(0, 0);return p;}void term_read(poly_t p){int i, n;int c, e;   scanf("%d\n", &n);for(i = 0; i < n; i++){scanf("%d_%d\n", &c, &e);p->tail = p->tail->next = TERM(c, e);}}poly_t poly_destory(poly_t p){link t, x;for(t = p->head; t; free(t), t = x)x = t->next;free(p);return NULL;}void poly_show(poly_t p){link t;if(p->head == p->tail)return;for(t = p->head->next; t != p->tail; t = t->next){printf("%dX^%d_%c_", (t->c > 0) ? (t->c) : (-t->c), t->e, (t->next->c > 0) ? '+' : '-');}printf("%dX^%d\n", (t->c>0) ? (t->c):(-t->c), t->e);}poly_t poly_add(poly_t p1, poly_t p2){poly_t p = poly_init();link t1 = p1->head->next;link t2 = p2->head->next;while(t1 && t2){if(t1->e < t2->e){p->tail = p->tail->next = TERM(t1->c, t2->e);t1 = t1->next;}else if(t1->e > t2->e){p->tail = p->tail->next = TERM(t2->c, t2->e);t2 = t2->next;}else{int sum = t1->c + t2->c;if(sum != 0){p->tail = p->tail->next = TERM(sum, t1->e);}t1 = t1->next;t2 = t2->next;}}for(; t1; t1 = t1->next){p->tail = p->tail->next = TERM(t1->c, t1->e);}for(; t2; t2 = t2->next){p->tail = p->tail->next = TERM(t2->c, t2->e);}return p;}int main(){poly_t p1, p2, p3;p1 = poly_init();term_read(p1);poly_show(p1);p2 = poly_init();term_read(p2);poly_show(p2);p3 = poly_add(p1, p2);poly_show(p3);poly_destory(p1);poly_destory(p2);poly_destory(p3);return 0;}




著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.