c ++中链接结构的数组

时间:2017-03-27 05:48:00

标签: c++ arrays struct

我想创建一个链接结构数组,但我不知道如何填充这样的数组。这是我想要做的一个例子。

struct foo {
    int data;
    foo* next;
};

我想在循环中声明数组

while(1) {
    foo array[n];
    // init array, data to -1 and next to NULL;

我想将内容放入其中,创建foo的新实例,使得所有foo链接在索引i中共享一个公共属性。

    foo* new_foo = new foo;
    new_foo -> data = x;
    new_foo -> next = array + i; // index
    array[i] = *new_foo;

    //do things
    iterate(array);

    //delete[] array; maybe
} // end loop, start again with a new array.

迭代方法就是这样的。

for(int i=0; i<n; ++i) {
    foo* iter = array + i;
    while(iter != NULL) {
        //do things
        iter = iter -> next;
    }
}

它根本不起作用,迭代方法进行无限循环。错误可能在其他地方,但我仍然不知道这是否是正确的做法。我知道我也必须在某处使用删除。我还是c ++的新手,我喜欢你的任何建议。谢谢!

编辑:

如果有人想知道的话,这很好。

foo* array[n] = {NULL};

foo* new_foo = new foo;
new_foo -> data = x;
new_foo -> next = array[i];
array[i] = new_foo;

1 个答案:

答案 0 :(得分:1)

从我通过您的问题理解,您需要一种方法来填充链接的结构并迭代它。如果我错了,请纠正我。

让我们说如果你想填充n个结构。

foo* new_foo = new foo;
new_foo -> data = 1;
foo* head = new_foo; // store a starting pointer to the linked list
foo* prev = new_foo;
i=2;
while(i<=n)
{
  foo* new_foo = new foo;
  new_foo -> data = i++;
  prev -> next = new_foo; 
  prev=new_foo;
}
prev->next=NULL;

现在,如果您希望迭代并对填充的列表执行操作。

foo* iter =head;
while(iter!=NULL)
{
  //do things
  iter=iter->next;
}

现在你想要一个这样的Linked结构数组,你可以将所有链接结构的头指针存储在一个数组中。