2013-04-01 32 views
1

這是我將兩個鏈接列表合併在一起的代碼。當我運行它時,出現了分段錯誤和核心轉儲錯誤。我不知道如何解決它。我的大腦油炸請幫忙。C++合併兩個鏈接列表分段錯誤和核心轉儲錯誤

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

1)啓動'gdb'加載你的可執行文件2)運行並崩潰3)讀取棧跟蹤4)突然顯示並修復 –

+0

...或者只是使用Valgrind。 – TC1

回答

0

在該方法中merge

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

應改爲

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

我認爲你可以弄清楚爲什麼。