标题:C语言 多项式相加 链表 萌新求助大佬
只看楼主
jacklove4396
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2018-9-24
 问题点数:0 回复次数:0 
C语言 多项式相加 链表 萌新求助大佬
#include<stdio.h>
#include<malloc.h>
typedef struct node{
    int eocf;//序数
    int expn;//指数
    struct node *next;
}PolyNode;
PolyNode *CreatList (){
    int i,p=3;
    PolyNode *head=(PolyNode*)malloc(sizeof(PolyNode));
    PolyNode *tail=head;
    tail->next=NULL;
    for(i=0;i<p;i++){
        PolyNode *New=(PolyNode*)malloc(sizeof(PolyNode));
        printf("请输入第%d个节点的序数\n",i+1);
        scanf("%d",&New->eocf);
        printf("请输入第%d个节点的指数\n",i+1);
        scanf("%d",&New->expn);
        tail->next=New;
        New->next=NULL;
        tail=New;
    }
    return head;
}
void PrintList(PolyNode *head)
{
    PolyNode *tail=head;
    while(tail->next){
    tail=tail->next;
    printf("序数为%d,指数为%d\n",tail->eocf,tail->expn);        
    }
    printf("\n");   
}
PolyNode *Add (PolyNode *pa,PolyNode *pb)
{
    PolyNode *pc=(PolyNode*)malloc(sizeof(PolyNode));
    PolyNode *tail=pc;
    pa=pa->next;
    pb=pb->next;
    while(pa && pb ){
        if (pa->expn<pb->expn){
            tail->next=pa;
            tail=tail->next;
            pa=pa->next;
        }
        if (pa->expn>pb->expn){
            tail->next=pb;
            tail=tail->next;
            pb=pb->next;
        }
        else{
            pa->eocf=pa->eocf+pb->eocf;
            tail->next=pa;
            tail=tail->next;
            pa=pa->next;
            pb=pb->next;
        }
    }
    if (pa=NULL){
        tail->next=pb;
    }
    if (pb=NULL){
        tail->next=pa;
    }   
    return pc;
   
   
}
main()
{
   
    PolyNode *a=CreatList();
    PolyNode *b=CreatList();
    PrintList(a);
    PrintList(b);
    PolyNode *c=Add(a,b);
    PrintList(c);
   
}
搜索更多相关主题的帖子: malloc next head NULL pb 
2018-09-24 18:12



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-489977-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.044639 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved