首页 > 解决方案 > 输入第二个多项式后如何修复分段错误?

问题描述

我想使用链表添加两个多项式。但是在第二个链表中输入第二个多项式后,我遇到了分段错误。

当我尝试打印多项式 1 时,幂本身仍为 1,但不会递增。正在尝试所有可能的错误,所以代码可能有点笨拙。

 #include<bits/stdc++.h>
 using namespace std;
 struct node{
  int coef;
  int po;
  node *next;
 }*start1=NULL,*go,*go2,*start2=NULL;
int main()
{
int d1,d2;
cout<<"Enter degree of poly 1 :";
cin>>d1;
cout<<"Enter degree of poly 2 :";
cin>>d2;
int i,c,p;
cout<<"Polynomial 1:" ;
for(i=0;i<=d1;i++)
{   p=1;

    cout<<"Enter coeff of po  "<<i<<" : " ;
    cin>>c;
    node *temp=new node;

    temp->po=p;
    p=p+1;
    temp->coef=c;
    temp->next=NULL;
    go=start1;
    if(start1==NULL)
    {
        start1=temp;
        continue;
    }
    while ((go->next)!=NULL)
    {
        go=go->next;
    }
    go->next=temp;
    p=p+1;
}
cout<<"Polynomial 2 :";
for(i=0;i<=d2;i++)
{   p=1;
    cout<<"Enter coeff of po "<<i<<" :";
    cin>>c;
    node *temp2=new node;
    temp2->po=p;
    temp2->coef=c;
    temp2->next=NULL;
    go2=start2;
    if(start2==NULL)
    {
        start2=temp2;
        continue;
    }
    while ((go2->next)!=NULL)
    {
        go2=go2->next;
        cout<<"kk";
    }

    go2->next=temp2;
    p=p+1;
}       
go=start1;
while(go!=NULL)
{
    go2=start2;
    while(go2->next !=NULL)
    {
        if((go->po)==(go2->po))
        {
            go->coef = go->coef + go2->coef;
        }
        go2=go2->next;
    }
    go=go->next;
}
    go=start1;
cout<<"Resultant Polynomial : ";
for(i=0;i<=d1;i++)
{
    cout<<go->coef<<"^"<<i+1<<" + ";
    go=go->next;
}

我预计权力会增加,但它保留为 1 并且我遇到了分段错误

标签: c++linked-listsingly-linked-list

解决方案


程序崩溃的原因是这里:

cout << "Resultant Polynomial : ";
for (i = 0; i <= d1; i++)
{
    cout << go->coef << "^" << i + 1 << " + ";

go是一个空指针。这是因为在这个片段之前,你有这个循环:

while (go != NULL)
    { ... }

所以当这个循环结束时,go是一个空指针,因为循环不会以其他方式结束(否则它不会break或终止)。您的意思是go在此循环之后设置为不同的初始值吗?


在不相关的注释上,请阅读为什么我不应该#include <bits/stdc++.h>?为什么是“使用命名空间标准;被认为是不好的做法?


推荐阅读