Generic linked list in c++

Posted by itsaboy on Stack Overflow See other posts from Stack Overflow or by itsaboy
Published on 2011-06-28T15:03:53Z Indexed on 2011/06/29 8:23 UTC
Read the original article Hit count: 287

Filed under:
|
|

I have been struggling for too long a time now with a rather simple question about how to create a generic linked list in c++. The list should be able contain several types of structs, but each list will only contain one type of struct. The problem arises when I want to implement the getNode() function [see below], because then I have to specify which of the structs it should return. I have tried to substitute the structs with classes, where the getNode function returns a base class that is inherited by all the other classes, but it still does not do the trick, since the compiler does not allow the getNode function to return anything but the base class then.

So here is some code snippet:

typedef struct struct1 
{
    int param1;
(...)
} struct1;

typedef struct struct2 
{
    double param1;
(...)
} struct2;


typedef struct node
{
    struct1 data;
    node* link;
} node;

class LinkedList
{
public:
    node *first;
    int nbrOfNodes;
    LinkedList();
    void addNode(struct1);
    struct1 getNode();
    bool isEmpty();
};

LinkedList::LinkedList()
{
    first = NULL;
    nbrOfNodes = 0;
}

void LinkedList::addNode(struct1 newData)
{
    if (nbrOfNodes == 0)
    {
        first = new node;
        first->data = newData;
    }
    else
    {
        node *it = first;
        for (int i = 0; i < nbrOfNodes; i++)
        {
            it = it->link;
        }
        node *newNode = new node;
        newNode->data = newData;
        it->link = newNode;
    }
    nbrOfNodes++;
}

bool LinkedList::isEmpty()
{
    return !nbrOfNodes;
}

struct1 LinkedList::getNode()
{
    param1 returnData = first->data;
    node* deleteNode = first;
    nbrOfNodes--;
    if (nbrOfNodes)
        first = deleteNode->link;
    delete deleteNode;
    return returnData;
}

So the question, put in one sentence, is as follows: How do I adjust the above linked list class so that it can also be used for struct2, without having to create a new almost identical list class for struct2 objects? As I said above, each instance of LinkedList will only deal with either struct1 or struct2. Grateful for hints or help

© Stack Overflow or respective owner

Related posts about c++

Related posts about struct