# ♪ ♪ ♪

• I'm trying to create my list from the array.

structure

``````template <typename T>
struct Node {
T data;
Node* next;
};
``````

function

``````template <typename T>
Node<T>* arrayToList(const T tab[], size_t size){
Node<T> *node = new Node<T>;
for(int i=0;i<size;i++){
node->data = tab[i];
node->next = new Node<T>;
}
}
``````

main

``````    int tabi[] = {2,1,4,3,6,5,7,8};
size_t sizei = sizeof(tabi)/sizeof(tabi[0]);
Node<int> *listAi = arrayToList(tabi,sizei);
``````

So the problem is, I can't rule the created copy Node here. `node->next = new Node<T>;` I'm making a copy of it, and how do you put a weight in it?

• I don't understand what your problem is.

So I'm gonna propose a code that allows the list to be filled with elements of the body. I hope that if it's not what you need, you will inform me in your commentary to the answer.

Here's the demonstration program.

``````#include <iostream>
template <typename T>
struct Node
{
T data;
Node *next;
};
template <typename T>
Node<T> * arrayToList( const T a[], size_t n )
{
for ( size_t i = 0; i &lt; n; i++, current = &amp;( *current )-&gt;next )
{
*current = new Node&lt;T&gt; { a[i], nullptr };
}

}
template <typename T>
{
}
int main()
{
int a[] = { 2, 1, 4, 3, 6, 5, 7, 8 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( int x : a ) std::cout &lt;&lt; x &lt;&lt; ' ';
std::cout &lt;&lt; std::endl;

Node&lt;int&gt; *list = arrayToList( a, N );

displayList( list );
std::cout &lt;&lt; std::endl;

}
``````

Its conclusion to the console:

``````2 1 4 3 6 5 7 8
2 1 4 3 6 5 7 8
``````

If your compiler doesn't support the initialization list for the operator. `new`the proposal

``````*current = new Node<T> { a[i], nullptr };
``````

you can replace the following proposals

``````*current = new Node<T>;
( *current )->data = a[i];
( *current )->next = nullptr;
``````

Either you can write for class. `Node` The designer, so that we can rewrite everything in one line like, for example,

``````*current = new Node<T>( a[i], nullptr );
``````

2

2

3

1

2

2

1

2

3

2

2

2

2

2

2