【发布时间】:2016-01-05 01:00:54
【问题描述】:
我在使用双向链表课程时遇到了一些困难,这是我大学项目的一部分。类的代码是这样的:
class container
{
public:
class node
{
public:
node * prev;
node * next;
int value;
};
container(int v);
node *start; // first element of the list
node *finish; // last element of the list
void insert_start(node *start, int val);
void print_container();
}
函数 insert_start 应该将元素添加到列表的开头。代码如下:
void container :: insert_start(node *start, int val)
{
if(start!=NULL)
{
cout << "in insert_start" << endl;
cout << "number added:" << val << endl;
node *element = new node;
element->value=val;
element->next=start;
start=element;
start->prev=NULL;
}
else
{
cout << "List is empty" << endl;
}
}
函数 print_container 应该打印我的链表。代码如下所示:
void container::print_container()
{
node *tmp;
tmp = start;
while(tmp!=nullptr)
{
cout << tmp->value << endl;
tmp=tmp->next;
}
}
很遗憾,我的程序存在两个问题。首先,它 似乎在数据结构的添加元素中添加了相同的随机值。其次,在执行函数 print_container 期间存在分段错误。我想这可能是 insert_start 函数中的一个错误(或多个错误),但我对此并不完全确定。
这是测试程序:
int main(void)
{
int how_many_pieces;
container L(6);
L.insert_finish(L.finish,3);
cout << "added element: " << L.finish->value << endl;
L.insert_start(L.start,8);
cout << "added element: " << L.start->value << endl;
L.insert_start(L.start,12);
cout << "added element: " << L.start->value << endl;
//show elements of the L list
L.print_container();
cout << "\n";
return 0;
}
感谢您的帮助。
【问题讨论】: