For starters it is a bad design. It does not make sense to initialize a node with elements of a vector.
It is a list that may be initialized by elements of a vector not a node.
The definition of the constructor ListNode
also does not make sense.
For example its data member next
is not initialized.
ListNode* ptr = next;
So this statement
ptr->next = tem;
invokes undefined behavior.
A node was allocated and then deleted
ListNode* tem = new ListNode(*it);
// ...
delete tem;
So what the list will contain?:)
Also it is a bad idea to use a typedef like this
typedef vector<int>::iterator vit;
It only confuses readers of the code.
The class can be defined the following way as it is shown in the demonstrative program. Of course you yourself need to append the class definition with other constructors, assignment operators and the destructor.
#include <iostream>
#include <vector>
class List
{
protected:
struct Node
{
int val;
Node *next;
} *head = nullptr;
public:
explicit List() = default;
List( const std::vector<int> &v )
{
Node **current = &head;
for ( const auto &value : v )
{
*current = new Node { value, *current };
current = &( *current )->next;
}
}
friend std::ostream & operator <<( std::ostream &, const List & );
};
std::ostream & operator <<( std::ostream &os, const List &list )
{
for ( List::Node *current = list.head; current != nullptr; current = current->next )
{
os << current->val << " -> ";
}
return os << "nullptr";
}
int main()
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List list( v );
std::cout << list << '\n';
}
The program output is
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> nullptr
As the constructor of the list that accepts a vector is not explicit then you may declare a list the following way
List list( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } );