Better way to create a linked list

It is very easy to declare and initialize an array like
int a[4] = {1,3,4,5};

Here is my attempt to create a linked list ;
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
29
30
31
32
33
34
35
#include<iostream>
using namespace std ;

typedef struct nodeType  {
    int info ;
    struct nodeType *next ;
}node;

node *head = NULL ;
int main(){
    cout<<"\nCreating a list.....";
    for(int i=1; i<=5;i++){
        node *ptr = new node ;
        node *prePoi;
        ptr->info = (i*5) ;
        if(head != NULL){
            prePoi->next = ptr ;
        }
        else {
            head = ptr;
        }
        prePoi = ptr ;
        if(i==5){
            ptr->next = NULL ;
        }
    }

    cout<<"\nThe elements in the list are ";
    node *loc = head;
    while(loc!= NULL){
        cout<<" "<<loc->info;
        loc = loc ->next ;
    }
   return 0;
}

Is there any easier and better way to do this ?
As I have to work on linked lists and I do not want to write the same code again and again.
Can I save the linked list onto a file ? If yes , then please point me in the right direction . Thanks
This is the easiest way to initialize and save a linked list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <list>
#include <fstream>

int main()
{
    std::list <int> l = {1, 3, 4, 5};

    std::ofstream savefile("save.txt");
    for(auto i : l) savefile << i << std::endl;

    std::list <int> loadedList;
    std::ifstream loadfile("save.txt");
    int i;
    while(loadfile >> i) loadedList.push_back(i);

    return 0;
}


If you're using g++ (or MinGW), compile with -std=C++0x
I use Codeblocks.
At last I could do the program , there was no requirement to be saved to a disk. It could have made things harder. If anyone needs to look at the code , do tell me . Thanks ..


Last edited on
Topic archived. No new replies allowed.