Ordered linked lists with classes help!

Hello there!
Im having trouble with creating an ordered linked list with C++ using classes (NOT STRUCTS!!!!!!!!!!!!!!!!!!!!)

I have previously done this before in C using structs. My solution to this problem was creating a separate function which sorts the linked list by using two pointers (a next and previous pointer), however I would like to make it so it adds to the correct position straight away (not adding everything then sorting it).

My attempt is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Node
class Node {
    int data;
    Node* next;

    public:
        Node() {};
        void SetData(int aData) { data = aData; };
        void SetNext(Node *aNext) { next = aNext; };
        int Data() { return data;};
        Node *Next() {return next;};
};

//List class
class List {
    Node *head;
    public:
        List() {head=NULL;};
        void Print();
        void Insert(int DATA);
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//add node to list
void List::Insert(int data) {

    // Create a new node
    Node* newNode = new Node();

    // Create a temp pointer
    Node *tmp = head;

    if(tmp != NULL) {
        while(tmp->Next() && tmp->Next()->Data() < data)
        {
            newNode->SetData(data);
            tmp=tmp->Next();
        }
        tmp->SetNext(newNode);
    } else {
        head = newNode;
    }
}


This just outputs rubbish :(

Im not trying to get someone to give me the solution straight away, but all help will be appreciated! If people can just give me tips and hints to get me on the right path that would be fantastic!
Firstly, this should be before your if statement:

newNode->SetData(data);

Secondly, when you link newNode into the list, you're linking tmp to newNode, but you haven't linked newNode to tmp->Next() (do this first, since you overwrite it when you call SetNext(newNode)).
Topic archived. No new replies allowed.