29

How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow?

peterh
  • 9,698
  • 15
  • 68
  • 87
jessemiel
  • 373
  • 2
  • 4
  • 11
  • 3
    he said he studies it himself and not for homework. i think it's not reasonable to add the homework tag then – Johannes Schaub - litb Dec 29 '08 at 16:01
  • @litb - Agreed. I just tweaked the tags. – Roddy Dec 29 '08 at 16:39
  • 2
    We do need a tag that describes when a user wants the code and it isn't homework. I nominate 'plzsendtehcodez'. – George Stocker Dec 29 '08 at 16:51
  • 2
    @Gortok - I don't think that's helpful. This isn't one of those "I want to write a 3d-shooter/create a botnet/question". It is a "simple" question, but still a reasonable one IMO. plzsendtehcodez is a prettyinsulting tag and should be used with a little more discretion... – Roddy Dec 29 '08 at 16:55
  • @Roddy You should have seen it before I edited it to be 'reasonable'. – George Stocker Dec 29 '08 at 20:37
  • @Gortok - hehe - fair point! However, it brings up another question: Should tags reflect the original question, or the current edit...? – Roddy Dec 29 '08 at 20:46
  • @Roddy: Great question. I have no idea. I still like the 'plzsendtehcodez' tag. – George Stocker Dec 29 '08 at 22:49

8 Answers8

43

I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.

First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++:

struct Node {
    int data;
    Node * next;
};

Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand:

Node a={1}, b={20, &a}, c={35, &b} d={42, &c};

Now, you have have a linked list of nodes, all allocated on the stack:

d -> c -> b -> a
42   35   20   1

Next step is to write a wrapper class List that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified):

class List {
    struct Node {
        int data;
        Node * next;
    };

    Node * head;

public:
    List() {
        head = NULL;
    }

    ~List() {
        while(head != NULL) {
            Node * n = head->next;
            delete head;
            head = n;
        }
    }

    void add(int value) {
        Node * n = new Node;
        n->data = value;
        n->next = head;
        head = n;
    }

    // ...
};

Next step is to make the List a template, so that you can stuff other values (not only integers).

If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.

Community
  • 1
  • 1
Johannes Schaub - litb
  • 466,055
  • 116
  • 851
  • 1,175
  • Taking above example, what would be the function to get respective data at respective head ? P.S im noob. – Vikrant Jun 13 '18 at 06:34
22

You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.

You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.

Roddy
  • 63,052
  • 38
  • 156
  • 264
15

If you are going to use std::list, you need to pass a type parameter:

list<int> intList;  
list<int>* intListPtr = new list<int>;

If you want to know how lists work, I recommending googling for some C/C++ tutorials to gain an understanding of that subject. Next step would then be learning enough C++ to create a list class, and finally a list template class.

If you have more questions, ask back here.

martijnn2008
  • 3,236
  • 3
  • 27
  • 38
karx11erx
  • 1,934
  • 2
  • 19
  • 32
9

Why reinvent the wheel. Just use the STL list container.

#include <list>

// in some function, you now do...
std::list<int> mylist; // integer list

More information...

mepcotterell
  • 2,510
  • 2
  • 20
  • 27
  • 3
    std::list is a parameterized type and new returns a pointer, your example should be more like: list* mylist = new list; or better yet, simply: list mylist; – Ferruccio Dec 29 '08 at 16:11
0

I'm guessing this is a homework question, so you probably want to go here. It has a tutorial explaining linked lists, gives good pseudocode and also has a C++ implementation you can download.

I'd recommend reading through the explanation and understanding the pseudocode before blindly using the implementation. This is a topic that you really should understand in depth if you want to continue on in CS.

brien
  • 4,171
  • 3
  • 27
  • 32
0

Boost ptr_list

http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_list.html

HTH

plan9assembler
  • 2,852
  • 1
  • 22
  • 13
0

Create list using C++ templates

i.e

template <class T> struct Node 
{
    T data;
    Node * next;
};
    
template <class T> class List 
{
    Node<T> *head,*tail;
        
    public: 
        void push(T const&);  // push element 
        void pop();           // pop element 
        bool empty()          // return true if empty. 
}; 

Then you can write the code like:

List<MyClass>;

The type T is not dynamic in run time.It is only for the compile time.

For complete example click here.

For C++ templates tutorial click here.

Yasitha Bandara
  • 1,093
  • 1
  • 11
  • 18
-3

We are already in 21st century!! Don't try to implement the already existing data structures. Try to use the existing data structures.

Use STL or Boost library

Vinay
  • 4,675
  • 7
  • 31
  • 42
  • 7
    Imo it's always a good idea to create some - simple - implementation of features or structures one tries to get a grasp of. ;) – karx11erx Dec 29 '08 at 16:22
  • 1
    I agree with karx. We had assignments like this in school and I would say, I am way more appreciative of the code that is already written, and more understanding of what it actually does because of it. A similar case would also be learning assembler. Knowledge of the abstracted is generally good. – Wes P Dec 29 '08 at 16:58
  • If it is a assignment then it is simple to implement, if it is a part of a larger project i.e., if it is used in a larger project to store the data then we should not implement we should use the existing library. – Vinay Dec 30 '08 at 01:11