♪ ♪ ♪
-
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 )
{
Node<T> *head = nullptr;
Node<T> **current = &head;for ( size_t i = 0; i < n; i++, current = &( *current )->next ) { *current = new Node<T> { a[i], nullptr }; } return head;
}
template <typename T>
void displayList( Node<T> *head )
{
for ( ; head; head = head->next ) std::cout << head->data << ' ';
}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 << x << ' '; std::cout << std::endl; Node<int> *list = arrayToList( a, N ); displayList( list ); std::cout << 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 );