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

Printing the polynomial using linked list data structure

本文关键字:打印 多项式 数据结构 链表      更新时间:2023-10-16

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

#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+

科里鲁的现场演示