使用链表数据结构打印多项式

时间:2018-09-22 10:29:56

标签: c++ data-structures linked-list polynomials

我编写了以下代码以使用链表打印2多项式。当我运行该程序时,它在输出中不打印任何内容。还请告诉我是否以这种方式从main()传递值,何时再次该函数将被调用,我的start1和start2将被更改,或者它们将保持为NULL。

#include <iostream>
using namespace std;
struct Node
{
    int coeff;
    int exp;
    Node* next;
};
void create_Poly(int x,  int y , Node *start)
{
    Node *temp,*ptr;
    if(start==NULL)
    {
        temp=new Node;
        temp->coeff=x;
        temp->exp=y;
        temp->next=NULL;
    }
    else
    {
            ptr = start;
            while(ptr->next!=NULL)
            {
                ptr=ptr->next;
            }
             temp = new Node;
             temp->coeff=x;
             temp->exp=y;
             temp->next=NULL;
             ptr->next=temp;
    }
    //return start;
}
void display(Node *start)
{
    Node * print = start;
    while(print!=NULL)
    {
        cout<<print->coeff<<"^"<<print->exp<<"+";
        print=print->next;
    }
    cout<<endl;
}
int main()
{
    struct Node * start1=NULL,*start2=NULL;
    create_Poly(3,2,start1);
    create_Poly(3,2,start1);
    create_Poly(3,2,start1);
    display(start1);
    create_Poly(4,2,start2);
    create_Poly(4,2,start2);
    display(start2);
}

1 个答案:

答案 0 :(得分:0)

@Scheff告诉我,开始从未改变过,我改变了开始,这里是代码

#include <iostream>
using namespace std;
struct Node
{
    int coeff;
    int exp;
    Node* next;
};
void create_Poly(int x,  int y , Node *&start)
{
    Node *temp,*ptr;
    if(start==NULL)
    {
        temp=new Node;
        temp->coeff=x;
        temp->exp=y;
        temp->next=NULL;
        start=temp;
    }
    else
    {
            ptr = start;
            while(ptr->next!=NULL)
            {
                ptr=ptr->next;
            }
             temp = new Node;
             temp->coeff=x;
             temp->exp=y;
             temp->next=NULL;
             ptr->next=temp;
    }
    //return start;
}
void display(Node *start)
{
    Node * print = start;
    while(print!=NULL)
    {
        cout<<print->coeff<<"^"<<print->exp<<"+";
        print=print->next;
    }
    cout<<endl;
}
int main()
{
    struct Node * start1=NULL,*start2=NULL;
    create_Poly(3,2,start1);
    create_Poly(3,2,start1);
    create_Poly(3,2,start1);
    display(start1);
    create_Poly(4,2,start2);
    create_Poly(4,2,start2);
    display(start2);
}

输出:

3^2+3^2+3^2+
4^2+4^2+

Live Demo on coliru

相关问题