[英]Array of linked structs in c++
我想創建一個鏈接結構的數組,但是我不知道如何填充這樣的數組。 這是我想做的一個例子。
struct foo {
int data;
foo* next;
};
我想在循環中聲明數組
while(1) {
foo array[n];
// init array, data to -1 and next to NULL;
我想把東西放進去,以新的方式創建foo 實例 ,使索引中鏈接的所有foo共享一個公共屬性。
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;
根據您對問題的理解,您需要一種方法來填充鏈接的結構並對其進行迭代。 如果我錯了,請糾正我。
假設您要填充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結構的數組,您可以將所有Linked結構的頭指針存儲在數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.