How to make a linked list.

How can you make a linked list without having to write


node *head = NULL;


1
2
3
head = new node ( "zildjian" );
	head->next =  new node ("sabian");		
	head->next->next = new node ("paiste" );


Last edited on
std::list<T> list;
No templates , I know it's a for loop but I can't think of the right algorithm.
This is one way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <string>
#include <iostream>

struct node
{
    explicit node( const std::string& v, node* n ) : value(v), next(n) {}
    ~node() { delete next ; }
    // ... deleted copy amd move ...

    std::string value ;
    node* next ;
};

node* make_list( const std::string* names, std::size_t n )
{
    if( n == 0 ) return nullptr ;
    else return new node( names[0], make_list( names+1, n-1 ) ) ;
}

int main()
{
    const std::string names[] = { "zildjian", "sabian", "paiste", "etc." } ;

    node* n = make_list( names, sizeof(names) / sizeof(*names) ) ;
    for( ; n ; n = n->next ) std::cout << n->value << '\n' ;

    delete n ;
}


http://liveworkspace.org/code/nTQDf$0
thanks
Topic archived. No new replies allowed.