欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C语言单链表实现多项式相加

时间:2021-10-18 10:05:35|栏目:C代码|点击:

本文实例为大家分享了C语言单链表实现多项式相加的具体代码,供大家参考,具体内容如下

//多项式的相加和相乘 
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)//兼容scanf
typedef struct node {
  int coef;
  int expon;
  struct node* link;
}Polynode,*Polynomial;
Polynomial InsertPolyLinklist(Polynomial in,Polynomial Pread) {
  Pread->link = in;
  Pread = in;
  in->link = NULL;
  return Pread;
}
Polynomial ReadPoly(void) {

  Polynomial Pread = (Polynomial)malloc(sizeof(Polynode));
  Pread->link = NULL;
  Polynomial H = Pread;
  int N;
  scanf("%d ", &N);
  while (N--) {
    Polynomial p = (Polynomial)malloc(sizeof(Polynode));
    scanf("%d %d", &p->coef, &p->expon);
    Pread= InsertPolyLinklist(p,Pread);
  }
  Polynomial F;
  F = H->link;
  free(H);
  return F;
}
void PrintPoly(Polynomial F) {
  while(F != NULL) {
    printf("%d %d ", F->coef, F->expon);
    F = F->link;
  }
  printf("\n");
}
Polynomial Add(Polynomial p1, Polynomial p2) {
  Polynomial t1=p1,t2=p2;
  Polynomial p=(Polynomial)malloc(sizeof(Polynode));
  p->link = NULL;
  Polynomial q = p;
  Polynomial read;
  while (t1&&t2) {
    if (t1->expon == t2->expon) {
      if (t1->coef + t2->coef) {
        t1->coef = t1->coef + t2->coef;
        t1->expon = t1->expon;
        read = t1;
        q->link = read;
        q = read;
        t1 = t1->link;
        t2 = t2->link;   
      }
    }
    else {
      if (t1->expon > t2->expon){
        read = t1;
        q->link = read;
        q = read;
        t1 = t1->link;
      }
      else {
        if (t1->expon < t2->expon) {
          read = t2;
          q->link = read;
          q = read;
          t2 = t2->link;
        }
      }
    }
  }    
  if (t1) {
    q->link = t1;
  }
  if (t2) {
    q->link = t2;
  }
  Polynomial F = p->link;
  free(p);
    return F;
}
int main(void) {
  Polynomial p1, p2, pp, ps;
  p1 = ReadPoly();
  PrintPoly(p1);
  p2 = ReadPoly();
  PrintPoly(p2);
  pp = Add(p1, p2);
  PrintPoly(pp);
// ps = Mult(p1, p2);
// PrintPoly(ps);
  return 0;
}

参考

MOOC 浙大数据结构

上一篇:C++控制台实现俄罗斯方块游戏

栏    目:C代码

下一篇:VC++的if语句应用范围分析

本文标题:C语言单链表实现多项式相加

本文地址:http://www.codeinn.net/misctech/180374.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有