c++合并两个链表分段错误和核心转储错误
C++ merging two linked lists segmentation fault and core dump error
这是我合并两个链表的代码。当我运行它时,我得到一个分段错误和核心转储错误。我不知道该怎么补救。我脑子坏了,请帮帮我。
#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;
}
我想你知道为什么。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)