我试图让链接类似的列表太这里的一个:C++链表
这是有“头”,我第一次把它称为,另一个结构里面。不过,我发现正在做这种改变。很难将值添加到list_item结构中。我已经尝试了几件事情,看它是否有效。它编译,但是当我运行代码时它会崩溃。任何帮助在这里都会有所帮助。我知道崩溃的原因是我想将new_node指向linked_list。
#include <iostream>
using namespace std;
struct list_item
{
int key;
int value;
list_item *next;
};
struct list
{
struct list_item *first;
};
int main()
{
list *head;
list *new_node;
head = NULL;
head->first = NULL;
for(int i = 0; i < 10; i++)
{
//allocate memory for new_node
new_node = (list*)malloc(sizeof(list));
new_node->first = (list_item*)malloc(sizeof(list_item));
//adding the values
new_node->first->key = i;
new_node->first->value = 10 + i;
//point new_node to first;
new_node->first->next = head->first;
//point first to new_node;
head->first = new_node->first;
}
//print
list *travel;
travel->first = head->first;
int i = 0;
while(travel != NULL)
{
cout << travel->first->value << endl;
travel->first = travel->first->next;
}
return 0;
}
请注意,C++已将std :: list <>作为标准容器提供给您。出于这个原因,我删除了你的C++标签。 – ChrisInEdmonton 2009-11-28 16:43:26
如果它将被标记为C而不是C++,请使用结构而不是类,而使用malloc而不是运算符new,我很想编辑它以开始使用printf,停止投射malloc的返回值,而不依赖于implicit typedef from struct definition:P – asveikau 2009-11-28 16:49:53