【问题标题】:C++ merging two linked lists segmentation fault and core dump errorC ++合并两个链表分段错误和核心转储错误
【发布时间】:2013-04-01 20:22:43
【问题描述】:

这是我将两个链表合并在一起的代码。当我运行它时,我得到一个分段错误和核心转储错误。我不知道如何解决它。我的大脑被炸了,请帮忙。

#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);
}

【问题讨论】:

  • 1) 开始 gdb 加载您的可执行文件 2) 运行并崩溃 3) 读取堆栈跟踪 4) 顿悟并修复
  • ...或者只使用 Valgrind。

标签: c++ linked-list segmentation-fault coredump


【解决方案1】:

merge方法中

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

应该改为

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

我想你可以弄清楚原因。

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2022-01-14
    相关资源
    最近更新 更多