一元多项式相加

#define NULL 0
#include "stdio.h"
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef struct LNode
{
    int cofe,expn;
    struct LNode * next;
} LNode,*Linklist; /*建立结构体*/
void creatlist (Linklist La)
{
    Linklist s,tem;
    int i,n;
    //p=La;
    scanf("%d",&n);/*手动输入n,控制n的项数*/
    for(i=0; i<n; i++)
    {
        s=(Linklist)malloc(sizeof(LNode));
        scanf("%d,%d",&s->cofe,&s->expn);
        tem=La->next;
        if(tem==NULL||s->expn>tem->expn){
            La->next=s;
            s->next=tem;
            cout<<"frist"<<endl;
        }
        else
        for(;tem&&tem->next;tem=tem->next){
            if(tem->expn==s->expn){
                tem->cofe+=s->cofe;
                break;
            }
            if(tem->expn>s->expn&&tem->next->expn<s->expn){
                s->next=tem->next;
                tem->next=s;
            }
        }
        //p->next=s;
        //s->next=NULL;
    }
}/*建立单链表的被调函数*/
int main()
{
    Linklist La,Lb,Lc,p,q,r;
    La=(Linklist)malloc(sizeof(LNode));
    La->next=NULL;/*开辟头结点*/
    creatlist(La);/*调用*/
    printf("List1 is:\n");
    for(p=La->next; p; p=p->next)
        printf("%4d,%4d",p->cofe,p->expn);/*输出单链表*/
    Lb=(Linklist)malloc(sizeof(LNode));
    Lb->next=NULL;
    creatlist(Lb);
    printf("List2 is:\n");
    for(p=Lb->next; p; p=p->next)
        printf("%4d,%4d",p->cofe,p->expn);
    Lc=(Linklist)malloc(sizeof(LNode));
    Lc->next=NULL;
    q=Lb->next;
    p=La->next;
    r=Lc;/*定义两个指针*/
    while(p&&q)
    {
        if(p->expn==q->expn)
        {
            p->cofe+=q->cofe;
            r->next=p;
            r=p;
            p=p->next;
            q=q->next;
        }
        else if(p->expn>q->expn)
        {
            r->next=q;
            r=q;
            q=q->next;
        }
        else
        {
            r->next=p;
            r=p;
            p=p->next;
        }
    }
    if(p==NULL)
        r->next=q;
    else
        r->next=p;
    /*free(La);
    free(Lb); */
    printf("\nList3 is:\n");
    for(r=Lc->next; r; r=r->next)
        printf("%4d,%4d",r->cofe,r->expn);
    getchar();
    return 0;
}
View Code

帮某个小屁孩调试的,先存一下代码

posted @ 2014-12-02 11:53  JarvisLau  阅读(133)  评论(0编辑  收藏  举报