繁体   English   中英

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

[英]Printing the polynomial using linked list data structure

我编写了以下代码来使用链表打印 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);
}

它像@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+

在coliru上进行现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM