这段代码目的: 构造有序链表, 实现 merge 操作,将两个有序表合并,并且去重.
例子:
A: 1 2 2 3
B: 1 3 5 8
合并得C
C: 1 2 3 5 8
下面代码有一句错了,导致段错误,
如何调试呢/
#include <cstdio>
#include <algorithm>
class my_list
{
private:
struct node
{
int data;
struct node *next;
node(int data)
{
this->data = data;
next = NULL;
}
};
node* head;
node** find(int data); //get pointer to the 'next' member of node before data
node* pop();
public:
my_list();
void sorted_insert(int data);
my_list merge(my_list& B);
void show();
};
my_list::node** my_list::find(int data)
{
node **tmp = &head;
while(*tmp != NULL && (*tmp)->data < data)
{
tmp = &(*tmp)->next;
}
return tmp;
}
my_list::node* my_list::pop()
{
my_list::node *tmp = NULL;
if (head != NULL)
{
my_list::node* tmp = head;
head = head->next;
}
return tmp;
}
my_list::my_list()
{
head = NULL;
}
void my_list::sorted_insert(int data)
{
my_list::node **tmp = find(data);
my_list::node* new_node = new node(data);
new_node->next = *tmp;
*tmp = new_node;
}
void my_list::show()
{
my_list::node *tmp = head;
while(tmp != NULL)
{
printf("%-3d-> ", tmp->data);
tmp = tmp->next;
}
printf("NULL\n");
}
my_list my_list::merge(my_list& B)
{
my_list C;
my_list::node **c_tail, *tmp;
c_tail = C.find(0);
int last = 0;
if (head!=NULL && B.head!=NULL)
{
last = std::min(head->data, B.head->data) -1; //assure last no conflict
}
while(head!=NULL && B.head!=NULL)
{
if (head->data < B.head->data)
{
tmp = this->pop();
}
else
{
tmp = B.pop();
}
if (tmp->data != last)
{
last = tmp->data;
*c_tail = tmp;
tmp->next = NULL;
c_tail = &(*c_tail)->next;
}
else
{
delete tmp;
}
}
while(head != NULL)
{
tmp = this->pop();
if (tmp->data != last)
{
last = tmp->data;
*c_tail = tmp;
tmp->next = NULL;
c_tail = &(*c_tail)->next;
}
else
{
delete tmp;
}
}
while(B.head != NULL)
{
tmp = B.pop();
if (tmp->data != last)
{
last = tmp->data;
*c_tail = tmp;
tmp->next = NULL;
c_tail = &(*c_tail)->next;
}
else
{
delete tmp;
}
}
return C;
}
int main()
{
my_list A,B,C;
A.merge(B).show();
A.sorted_insert(1);
for (int i=5; i>=-1; i--)
{
A.sorted_insert(i);
}
B.sorted_insert(30);
B.sorted_insert(1);
B.sorted_insert(8);
B.sorted_insert(3);
A.show();
B.show();
C = A.merge(B);
C.show();
A.show();
B.show();
for (int i=0; i<5; i++)
{
A.sorted_insert(1);
B.sorted_insert(3);
}
C = A.merge(B);
return 0;
}
使用gdb调试core文件
g++ -ggdb -o list list.cpp
ulimit -c unlimited
gdb --tui ./list core
bt
可以看到时merge的时候, tmp 居然是NULL!
因为head都不是NULL,
所以可以判断时 pop函数出问题了.
仔细观察或者 监视pop的返回值,
可发现是 tmp重复定义了,因此 pop总是返回 NULL.