我写了一个双链表:
class doubled {
private:
class sublink {
private:
char data[30];
sublink *next_ptr;
sublink *previous_ptr;
friend doubled;
};
public:
sublink *first_ptr;
doubled(){first_ptr = NULL;};
void add_item(char *item);
void rm_item(char *item);
};
问题在于将项目添加到列表的功能:
void doubled::add_item(char *item){
sublink *new_data;
sublink *n_insert;
sublink *p_insert;
new_data = new sublink;
n_insert = new sublink;
p_insert = new sublink;
if(first_ptr == NULL){
strcpy(new_data->data, item);
new_data->previous_ptr = NULL;
new_data->next_ptr = first_ptr;
first_ptr = new_data;
} else {
strcpy(new_data->data, item);
n_insert = first_ptr;
while(1){
n_insert = n_insert->next_ptr;
if(n_insert == NULL)
break;
if(strcmp(n_insert->data, new_data->data) >= 0){
new_data->next_ptr = n_insert;
n_insert->previous_ptr = new_data;
}
}
p_insert = first_ptr;
while(1){
p_insert = p_insert->next_ptr;
if(p_insert == NULL)
break;
if((strcmp(p_insert->data, new_data->data)) < 0){
new_data->previous_ptr = p_insert;
p_insert->next_ptr = new_data;
}
}
}
std::cout << first_ptr->data << '\n';
std::cout << new_data->data << '\n';
if(new_data->next_ptr != NULL)
std::cout << new_data->next_ptr->data << '\n';
}
上面的代码按字母顺序将给定项目插入到列表中。
程序输出first_ptr->data
和new_data->data
,但不输出new_data->next_ptr->data
,也不输出first_ptr->next_ptr->data
。所以这句话if(new_data->next_ptr != NULL)
总是正确的,不应该是正确的。
有人看到这个程序的问题吗?