创建一个节点指针数组

问题描述:

  struct Node {
      int data;        // The data being stored at the node
      Node *next;     // Pointer to the next node
      };

int main()
{
         Node **nodeArray = new (Node*)[5];
}

第一个问题:

main语句是创建5个Node *的数组的有效方法吗?

Is the statement in main a valid way to create an array of 5 Node * 's ?

main语句与 Node ** nodeArray = new Node * [5]; ? Main当前给我一个错误:带括号的type-id |

What is the difference between the statement in main and Node **nodeArray = new Node*[5];? Main currently gives me an error: array bound forbidden after parenthesized type-id|

第二个问题:

如何我将遍历数组并为每个数组做一个新的吗?我曾经使用过数组,也曾经使用过链表,但是将它们组合在一起似乎比我想象的要难。

How would I go through the array and do a new for each one of them? I've worked with arrays and I've worked with linked lists, but putting them together seems trickier than I'd thought.

如果您知道最多需要5个项目,则应该使用静态分配,因为它更快,并且您不必担心会取消分配数组。

If you know that you need maximum of 5 items, you should use static allocation because it's faster and you don't have to worry about deallocating the array.

Node* array[SOME_CONST];
for (int i=0; i < SOME_CONST; i++)
{   
   array[i] = new Node()
   cout<<array[i];
}

对于动态分配的数组几乎是同一回事,您只需要意识到

For dynamically allocated arrays is pretty much the same thing, you just have to realize the pointer new returns points to the first item in the array.

Node** array = new Node*[some_num];
for (int i=0; i < some_num; i++)
{
   array[i] = new Node();
}

别忘了正确分配:

for (int i=0; i < some_num; i++)
{
   delete array[i];
}
delete[] array;