c语言单链表实现一元多项式相加算法

  • Post author:
  • Post category:其他




给定两个一元多项式,实现两个一元多项式的相加算法。提示:用一条单链表表示一个一元多项式,每个节点包含三个域:指数域、系数域和后继结点链。

可直接运行

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Node;
typedef struct Node *PNode;
struct Node
{
    int zhishu;
    int xishu;
    PNode next;
};
typedef struct Node *LinkList;
LinkList createNullList_link(void)//创建空链表
{
    LinkList llist = (LinkList)malloc(sizeof(struct Node));
    if(llist != NULL) llist -> next = NULL;
    else
    {
        printf("out of space!\n");
    }
    return llist;
}
PNode locate_link(LinkList llist,int zhishu)//求某元素的存储位置
{
    PNode p;
    if(llist == NULL) return NULL;
    p = llist->next;
    while(p != NULL && p->zhishu!=zhishu)p=p->next;
    return p;
}
int insertPost_link(LinkList llist,PNode p,int zhishu,int xishu)//在p节点后添加新节点
{
    PNode q = (PNode)malloc(sizeof(struct Node));
    if(q==NULL) {
        printf("out of space.");
        return 0;
    }
    else
    {
        q->zhishu=zhishu; 
        q->xishu=xishu;
        q->next=p->next;
        p->next=q;
        return 1;
    }
    
}
int main() 
{
    LinkList a1 = createNullList_link();
    insertPost_link(a1,a1,1,4);
    PNode p1 = a1->next;
    insertPost_link(a1, p1, 0, 5);
    LinkList a2 = createNullList_link();
    insertPost_link(a2, a2, 1, 6);
    PNode p2 = a2->next;
    insertPost_link(a2, p2, 0, 3);
    //以上设置好了两个一元多项式
    PNode p11 = locate_link(a1,1);
    PNode p21 = locate_link(a2, 1);
    PNode p10 = locate_link(a1, 0);
    PNode p20 = locate_link(a2, 0);
    int xishu1 = p11->xishu + p21->xishu;
    int xishu0 = p10->xishu+p20->xishu;
    printf("the sum is %d x + %d",xishu1,xishu0);
    return 0;
}



版权声明:本文为weixin_43490111原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。