zoukankan      html  css  js  c++  java
  • 多项式相加

    #include <stdio.h>
    #include <malloc.h>
    #define NULL 0
    struct node
    {
     int a,n;
     struct node *next;
    };
    struct node *creat()
    {
     int a,n;
     struct node *p1,*p2,*head;
     head=NULL;
     scanf("%d%d",&a,&n);
     p2=NULL;
     while(a)
     {
      p1=(struct node *) malloc(sizeof(struct node));
      p1->a=a;
      p1->n=n;
      p1->next=NULL;
      if(head==NULL)
      {
       head=p1;p2=p1;
      }  
            else
            {
             p2->next=p1;
       p2=p1;
            }
            scanf("%d%d",&a,&n);
     }
     return head;
    }

    struct node *add(struct node *head1,struct node *head2)
    {
     int a,n;
     struct node *p1=head1,*p2=head2,*head,*p3,*p4,*p;
     head=NULL;
     while(p1 && p2)
     {
      if(p1->n==p2->n)
      {
       a=p1->a+p2->a;
       n=p1->n;
       p1=p1->next;
       p2=p2->next;
      } 
      else
      {
       if(p1->n>p2->n)
       {
        a=p1->a;n=p1->n;
        p1=p1->next;
       }
       else
       {
        a=p2->a;n=p2->n;
        p2=p2->next;
       }
      }
      if(a)
      {
       p3=(struct node *)malloc(sizeof(struct node));
       p3->a=a;
       p3->n=n;
       p3->next=NULL;
       if(head==NULL)
       {
        head=p3;p4=p3;
       }
       else
       {
        p4->next=p3;
        p4=p3;
       }
      }
     }
     p=p1?p1:p2;
     while(p)
     {
      p3=(struct node *)malloc(sizeof(struct node));
      p3->a=p->a;
      p3->n=p->n;
      p3->next=NULL;
      if(head==NULL)
      {
       head=p3;p4=p3;
      }
      else
      {
       p4->next=p3;
       p4=p3;
      }
      p=p->next;
     }
     return head;
    }

    void print(struct node *head)
    {
     struct node *p1=head;
     if(head==NULL)
     {  printf("此多项式不存在 ");
           return ;
        }
     printf(" ");
     if(p1)
     {
              printf("%dx%d",p1->a,p1->n);
              p1=p1->next;
        }
     while(p1)
     {
      if(p1->a>0)
         printf("+");
            if(p1->n==0)
              printf("%d",p1->a);
            else
              if(p1->a==1)
                printf("x%d",p1->n);
              else
          printf("%dx%d",p1->a,p1->n);
      p1=p1->next;
     }
     printf(" ");
    }

    int main()
    {
     struct node *head1,*head2,*head3;
     head1=creat();
     head2=creat();
     print(head1);
     print(head2);
     head3=add(head1,head2);
     print(head3);
    }

  • 相关阅读:
    python数据库的增删改查
    Python基础教程笔记——第3章:使用字符串
    Python基础教程笔记——第2章:列表和元组
    Python基础教程笔记——第1章
    指针与数组的对比(——选自:C++内存管理技术内幕)
    C++内存分配方式(——选自:C++内存管理技术内幕)
    C++函数的重载,覆盖和隐藏(——高质量编程第14章)
    vim—基本命令1
    linux命令1——基础
    free delete malloc new(——高品质量程序设计指南第16章)
  • 原文地址:https://www.cnblogs.com/wc1903036673/p/3405955.html
Copyright © 2011-2022 走看看