c++合并两个链表分段错误和核心转储错误

C++ merging two linked lists segmentation fault and core dump error

本文关键字:错误 分段 核心 转储 链表 两个 合并 c++      更新时间:2023-10-16

这是我合并两个链表的代码。当我运行它时,我得到一个分段错误和核心转储错误。我不知道该怎么补救。我脑子坏了,请帮帮我。

#include<iostream>
using namespace std;
struct node
{
  int data;
  struct node *next;
};
class list
{
    struct node *start;
public:
    void create();
    void show();
    void merge(list,list);
};
void list::create()
{
  struct node *nxt_node, *pre_node;
  int value, no, i;
  start=nxt_node=pre_node=NULL;
  cout<<"nHow many nodes:";
  cin>>no;
  cout<<"Enter "<<no<<" Eelements:";
  for(i=1;i<=no;i++)
  {
    cin>>value;
    nxt_node=new node;
    nxt_node->data=value;
    nxt_node->next=NULL;
    if (start==NULL)
    start=nxt_node;
    else
    pre_node->next=nxt_node;
    pre_node=nxt_node;
  }
}
void list::show()
{
  struct node *ptr=start;

  while(ptr!=NULL)
  {
    cout<<ptr->data<<"->'";
    ptr=ptr->next;
  }
}
void list::merge(list l1,list l2)
{
  struct node *nxt_node, *pre_node, *pptr, *qptr;
  int dat;
  pptr=l1.start;
  qptr=l2.start;
  start=nxt_node=pre_node=NULL;
  while(pptr!=NULL && qptr!=NULL)
  {
   if(pptr->data<=qptr->data)
   {
        dat=pptr->data;
        pptr=pptr->next;
    }
    else
        {
    dat=qptr->data;
    qptr=qptr->next;
        }
    nxt_node=new node;
    nxt_node->data=dat;
    nxt_node->next=NULL;
    if(start==NULL)
    {   
     start=nxt_node;
    }   
    else
    {
     pre_node->next=nxt_node;
      pre_node=nxt_node;
    }
  }
  if(pptr==NULL)
  {
    while(qptr!=NULL)
    {
    nxt_node=new node;
    nxt_node->data=qptr->data;
    nxt_node->next=NULL;
    if(start==NULL)
       start=nxt_node;
    else
       pre_node->next=nxt_node;
       pre_node=nxt_node;
       qptr=qptr->next; 
    }
  }
  else if (qptr==NULL)
  {
    while(pptr!=NULL)
    {
        nxt_node=new node;
        nxt_node->data=pptr->data;
        nxt_node->next=NULL;
        if(start==NULL)
           start=nxt_node;
        else
           pre_node->next=nxt_node;
           pre_node=nxt_node;
           pptr=pptr->next;
    }
  }

}
int main()
{
    list l1,l2,l3;
    cout<<"Enter the first list in ascending order.";
    l1.create();
    cout<<"Enter the Second list in ascending order.";
    l2.create();
    cout<<"The first list is:"<<endl;
    l1.show();
    cout<<"The second list is"<<endl;
    l2.show();
    l3.merge(l1,l2);
    l3.show();

return (0);
}

方法merge

if(start==NULL)
{   
     start=nxt_node;
}   

改为

if(start==NULL)
{   
     start=nxt_node;
     pre_node=start;
}  

我想你知道为什么。